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)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…