19

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.

Max
  • 1,387
  • 1
  • 15
  • 29

1 Answers1

37

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)
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • 3
    Thanks for mentioning `Data(string.utf8)` – I missed that. `.nonLossyASCII` should also work, as it converts unicode characters to their escape sequence, e.g., `"ö".data(using: .nonLossyASCII)` = `\366`. – Max Sep 11 '17 at 10:40
  • How would I convert data to string – AbuTaareq Jan 25 '18 at 07:38
  • let newString = String(data: data!, encoding: String.Encoding.utf8) as String! – AbuTaareq Jan 25 '18 at 07:43
  • @AbuTaareq: A conversion from data to string can fail, so it would be `if let newString = String(data: data, encoding: .utf8) { ... }` – Martin R Jan 25 '18 at 08:28