Skip to content

common functions

ZefengYu edited this page Apr 7, 2016 · 2 revisions

@(swift)[kpw,swift,kindle]

swift common functions

[toc]

#####1.LOG 输出

func printLog<T>(message: T,  
                    file: String = __FILE__,
                  method: String = __FUNCTION__,
                    line: Int = __LINE__)
{
    #if DEBUG
    print("\((file as NSString).lastPathComponent)[\(line)], \(method): \(message)")
    #endif
}

#####2.FORMATTED OUTPUT The workaround is switching back to the original string formatting method, by using the init method of String:

let b = 1.234567
let format = String(format:"%.2f",b)
print("double:\(format)")
// Output:
// double:1.23

If we need to use a lot of formatting like this, a better way would be using an extension on Double:

extension Double {
    func format(f: String) -> String {
        return String(format: "%\(f)f", self)
    }
}

Now, the code is cleaner:

let f = ".2"
print("double:\(b.format(f))")
Clone this wiki locally