0

When converting String to Data, the most common answer online is use String.data(using:).

if let data = string.data(using: .utf8) {
    // process the data
}

Why not use String.utf8 to convert the string into a String.UTF8View collection and initialize a Data instance with Data.init(_:)?

let data = Data(string.utf8)

// process the data

Neither String.utf8 or Data.init(_:) return an optional, so no need for optional binding.

Jeffery Thomas
  • 42,202
  • 8
  • 92
  • 117
  • Because many people just don't know the API. `Data(string.utf8)` is state-of-the-art. – vadian Apr 11 '20 at 18:05
  • @vadian I remember when I figure that out in Swift 3 when Data started conforming to RandomAccessCollection. I've started spreading this approach a long time ago. – Leo Dabus Apr 11 '20 at 21:48
  • Note that converting string to utf8 will never fail so you can safely force unwrap the result – Leo Dabus Apr 11 '20 at 21:49
  • @vadian https://stackoverflow.com/revisions/28132610/5 Apr 4 '17 – Leo Dabus Apr 11 '20 at 22:07

0 Answers0