Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use String Encoding in Swift
Written by Team Kodeco

In Swift, you can use string encoding to convert a string to a specific encoding format, such as UTF-8, UTF-16, or ASCII. String encoding is useful when working with different systems and devices that may use different encoding formats.

Here’s how to use string encoding in Swift:

import Foundation

let message = "Hello, World!"

// You can use the data(using:) method to convert a string to a specific encoding format
let utf8Data = message.data(using: .utf8)
print(utf8Data) // Output: Optional(13 bytes)

You can also use the String(data:encoding:) initializer to convert a Data object to a string using a specific encoding format:

let data = "Hello, World!".data(using: .utf8)
let string = String(data: data!, encoding: .utf8)
print(string) // Output: Optional("Hello, World!")
© 2024 Kodeco Inc.