How do I serialize data with PropertyListEncoder/Decoder?

In Swift, you can serialize and deserialize data using the PropertyListEncoder and PropertyListDecoder. This is particularly useful when working with structured data formats like Property List (plist) files. Here's a basic example demonstrating how to encode and decode a simple struct using these encoders/decoders.

First, ensure your struct conforms to the Codable protocol. Then, you can easily encode an instance to a plist and decode it back.

// Define a struct that conforms to Codable struct User: Codable { var name: String var age: Int } // Create an instance of the struct let user = User(name: "John Doe", age: 30) // Encode the struct to a Property List let encoder = PropertyListEncoder() if let encodedData = try? encoder.encode(user) { // Save or use the encoded data print("Encoded user data: \(encodedData)") // Decode the data back to a User instance let decoder = PropertyListDecoder() if let decodedUser = try? decoder.decode(User.self, from: encodedData) { print("Decoded user: \(decodedUser)") } }

Swift PropertyListEncoder PropertyListDecoder Codable Serialization Deserialization Example