Xcode 8 ? Swift 3
extension Collection where Iterator.Element == UInt8 {
var bytes: [UInt8] { return Array(self) }
var data: Data { return Data(self) }
var string: String? { return String(data: data, encoding: .utf8) }
}
extension String {
var data: Data { return Data(utf8) }
}
usage:
let sentence = "Hello World"
let utf8View = sentence.utf8
let bytes = utf8View.bytes // [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
let data1 = sentence.data
print(data1 as NSData) // <48656c6c 6f20576f 726c64>
let data2 = utf8View.data
let data3 = bytes.data
let string1 = utf8View.string // "Hello World"
let string2 = bytes.string // "Hello World"
let string3 = data1.string // "Hello World"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…