Paul Calnan's Blog
Published April 17, 2023

We often need to convert between a String value and a Data value. I have been using the following approach for years to do this conversion:

func convert(from string: String) -> Data? {
    string.data(using: .utf8)
}

func convert(from data: Data) -> String? {
    String(data: data, encoding: .utf8) 
}

Note, I'm only using functions here so the return types are explicit. Usually I would just call String.data(using:) or String.init(data:encoding:) directly. The important part is that they both return optionals.

There is a way to do this without optionals.

func convert(from string: String) -> Data {
    Data(string.utf8)
}

func convert(from data: Data) -> String {
    String(decoding: data, as: UTF8.self)
}

The optional-based approach dates all the way back to iOS 2 and Objective-C. The non-optional approach came in around iOS 8 along with Swift.