print
自Swift的最新版本以来,功能已完全改变,现在看起来更加简单,并且有多种打印方法可以打印到标准控制台。
用于打印的方法签名看起来像这样,
public func print<Target>(_ items: Any..., separator: String = default, terminator: String = default, to output: inout Target) where Target : TextOutputStream
这里有一些用例,
print("Swift is awesome.")
print("Swift", "is", "awesome", separator:" ")
print("Swift", "is", "awesome", separator:" ", terminator:".")
印刷品:
Swift is awesome.
Swift is awesome
Swift is awesome.
级联
print("This is wild", terminator: " ")
print("world")
印刷品:
This is wild world
因此,使用终止符时,应注意内容与同一行相关。
使用CustomStringConvertible打印对象
struct Address {
let city: String
}
class Person {
let name = "Jack"
let addresses = [
Address(city: "Helsinki"),
Address(city: "Tampere")
]
}
extension Person: CustomStringConvertible {
var description: String {
let objectAddress = unsafeBitCast(self, to: Int.self)
return String(format: "<name: \(name) %p>", objectAddress)
}
}
let jack = Person()
print(jack)
印刷品:
<name: Jack 0x608000041c20>
CustomDebugStringConvertible
extension Person: CustomDebugStringConvertible {
var debugDescription: String {
let objectAddress = unsafeBitCast(self, to: Int.self)
let addressString = addresses.map { $0.city }.joined(separator: ",")
return String(format: "<name: \(name), addresses: \(addressString) %p>",objectAddress)
}
}
现在,使用lldb,您可以使用po 命令,它将在lldb控制台中按此方式打印对象,
<name: Jack, addresses: Helsinki,Tampere 0x60c000044860>
使用TextOutputStream记录到文件
struct MyStreamer: TextOutputStream {
lazy var fileHandle: FileHandle? = {
let fileHandle = FileHandle(forWritingAtPath: self.logPath)
return fileHandle
}()
var logPath: String = "My file path"
mutating func write(_ string: String) {
fileHandle?.seekToEndOfFile()
fileHandle?.write(string.data(using:.utf8)!)
}
}
现在,使用打印流,
print("First of all", to: &myStream )
print("Then after", to: &myStream)
print("And, finally", to: &myStream)
打印到文件:
First of all
Then after
And finally
CustomReflectable
extension Person: CustomReflectable {
var customMirror: Mirror {
return Mirror(self, children: ["name": name, "address1": addresses[0], "address2": addresses[1]])
}
}
现在,在lldb调试器中,如果使用命令po,
> po person
结果将是这样,
▿ <name: Jack, addresses: Tampere Helsinki 0x7feb82f26e80>
- name : "Jack"
▿ address1 : Address
- city : "Helsinki"
▿ address2 : Address
- city : "Tampere"