Skip to content

Convert Between String and Data in Swift

Convert String to Data

swift
let str = """
{
  "alg" : "HS256",
  "typ" : "JWT"
}
"""
let data = Data(str.utf8)
print(data)
let str = """
{
  "alg" : "HS256",
  "typ" : "JWT"
}
"""
let data = Data(str.utf8)
print(data)

or

swift
let str = """
{
  "alg" : "HS256",
  "typ" : "JWT"
}
"""

if let data = str.data(using: .utf8){  // or .ascii
    print(data)
}
let str = """
{
  "alg" : "HS256",
  "typ" : "JWT"
}
"""

if let data = str.data(using: .utf8){  // or .ascii
    print(data)
}

With this method, the return type is optional.

Convert Data to String

If you know an instance of Data contains a String and you want to convert it, you should use the String(decoding:as:) initializer, like this:

swift
let str = """
{
  "alg" : "HS256",
  "typ" : "JWT"
}
"""

if let data = str.data(using: .utf8){  // or .ascii
    let newStr = String(decoding: data, as: UTF8.self)
    print(newStr)
}
let str = """
{
  "alg" : "HS256",
  "typ" : "JWT"
}
"""

if let data = str.data(using: .utf8){  // or .ascii
    let newStr = String(decoding: data, as: UTF8.self)
    print(newStr)
}

If the Data instance can’t be converted to a UTF-8 string, you’ll get sent back an empty string.