print
fungsi telah berubah total sejak revisi terakhir Swift , sekarang terlihat lebih sederhana dan ada varian metode untuk mencetak ke konsol standar.
Tanda tangan metode untuk cetakan terlihat seperti ini,
public func print<Target>(_ items: Any..., separator: String = default, terminator: String = default, to output: inout Target) where Target : TextOutputStream
Dan berikut beberapa kasus penggunaan,
print("Swift is awesome.")
print("Swift", "is", "awesome", separator:" ")
print("Swift", "is", "awesome", separator:" ", terminator:".")
Cetakan:
Swift is awesome.
Swift is awesome
Swift is awesome.
Menggabungkan
print("This is wild", terminator: " ")
print("world")
Cetakan:
This is wild world
Jadi, dengan menggunakan terminator, Anda harus berhati-hati bahwa isinya relevan dengan baris yang sama.
Mencetak Objek dengan 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)
Cetakan:
<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)
}
}
Sekarang, dengan lldb , Anda dapat menggunakan perintah po dan itu akan mencetak objek seperti ini di konsol lldb,
<name: Jack, addresses: Helsinki,Tampere 0x60c000044860>
Masuk ke file menggunakan 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)!)
}
}
Sekarang, menggunakan print untuk streaming,
print("First of all", to: &myStream )
print("Then after", to: &myStream)
print("And, finally", to: &myStream)
Cetakan ke file:
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]])
}
}
Sekarang, di debugger lldb, jika Anda menggunakan perintah po,
> po person
Hasilnya akan seperti ini,
▿ <name: Jack, addresses: Tampere Helsinki 0x7feb82f26e80>
- name : "Jack"
▿ address1 : Address
- city : "Helsinki"
▿ address2 : Address
- city : "Tampere"