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
915 views
in Technique[技术] by (71.8m points)

swift - Can the conversion of a String to Data with UTF-8 encoding ever fail?

In order to convert a String instance to a Data instance in Swift you can use data(using:allowLossyConversion:), which returns an optional Data instance.

Can the return value of this function ever be nil if the encoding is UTF-8 (String.Encoding.utf8)?

If the return value cannot be nil it would be safe to always force-unwrap such a conversion.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

UTF-8 can represent all valid Unicode code points, therefore a conversion of a Swift string to UTF-8 data cannot fail.

The forced unwrap in

let string = "some string .."
let data = string.data(using: .utf8)!

is safe.

The same would be true for .utf16 or .utf32, but not for encodings which represent only a restricted character set, such as .ascii or .isoLatin1.

You can alternatively use the .utf8 view of a string to create UTF-8 data, avoiding the forced unwrap:

let string = "some string .."
let data = Data(string.utf8)

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

...