Swift version: 5.10
If you know an instance of Data
contains a String
and you want to convert it, you can use the String(decoding:as:)
initializer, like this:
let str = String(decoding: data, as: UTF8.self)
If the Data
instance can’t be converted to a UTF-8 string, you’ll might be sent back an empty string, but Swift might replace any bad characters with the Unicode replacement character. You do need to know which format is used to store the string, but UTF-8 is usually the best to go with.
If you're unsure about whether the string can safely be converted or not, there's a failable initializer you should use instead:
if let str = String(data: data, encoding: .utf8) {
print("Successfully decoded: \(str)")
}
Using this optional approach avoids any problems around decoding invalid strings – if it succeeds you can be sure the string that was loaded is intact and correct.
SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Available from iOS 8.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.