In Swift 3
let data = string.data(using: .utf8)
In Swift 2 (or if you already have a NSString
instance)
let data = string.dataUsingEncoding(NSUTF8StringEncoding)
In Swift 1 (or if you have a swift String
):
let data = (string as NSString).dataUsingEncoding(NSUTF8StringEncoding)
Also note that data
is an Optional<NSData>
(since the conversion might fail), so you'll need to unwrap it before using it, for instance:
if let d = data {
println(d)
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…