Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
584 views
in Technique[技术] by (71.8m points)

utf 8 - Swift 2.1 [UInt8] --utf8--> String?

I know questions like this exist on both Stack Overflow and elsewhere. But it seems to have evolved a lot as well.

Given a list of UInt8 (a swift byte array basically), what is the easiest/idiomatic way to covert it to a swift String?

I'm particularly interested in the method that doesn't use NSData/NSString, since if Santa brings Swift to the world of Linux, it will undoubtedly be without the NS libraries, and I'd like to know how to do it in just Swift.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...