将字符串转换为采用UTF-8编码的数据会失败吗?
为了在Swift中将String
实例转换为Data
实例,您可以使用data(using:allowLossyConversion:)
,它返回一个可选的Data
实例.
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.
如果编码为UTF-8(String.Encoding.utf8
),此函数的返回值是否可以为nil
?
Can the return value of this function ever be nil
if the encoding is UTF-8 (String.Encoding.utf8
)?
如果返回值不能为nil
,则始终强制展开此类转换是安全的.
If the return value cannot be nil
it would be safe to always force-unwrap such a conversion.
UTF-8可以表示所有有效的Unicode代码点,因此需要进行转换 Swift字符串转换为UTF-8数据不会失败.
UTF-8 can represent all valid Unicode code points, therefore a conversion of a Swift string to UTF-8 data cannot fail.
强行打开
let string = "some string .."
let data = string.data(using: .utf8)!
很安全.
对于.utf16
或.utf32
同样如此,但对于
仅代表受限字符集的编码,
例如.ascii
或.isoLatin1
.
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
.
您也可以使用字符串的.utf8
视图创建UTF-8数据,
避免强行打开包装:
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)