Search code examples
structencodingdecodinguserdefaults

How to Handle Encoding a Swift Struct Containing Swift Struct as Property


I have a requirement to persist a preferred Location that has been selected by a user. The Location contains a few properties:

public struct Location {

    // MARK: - Properties

    public let identifier: Int

    public let name: String

    public let address: Address?

    // MARK: - Initializations

    public init(identifier: Int, name: String, address: Address?) {
        self.identifier = identifier
        self.name = name
        self.address = address
    }

}

The Address follows:

public struct Address {

    // MARK: - Properties

    public let city: String?

    public let state: String?

    public let postalCode: String?

    public let country: String?

    // MARK: - Initialization

    public init(city: String?, state: String?, postalCode: String?, country: String?) {
        self.city = city
        self.state = state
        self.postalCode = postalCode
        self.country = country
    }

}

Since I only need to persist one Location at any given time, I prefer to use UserDefaults.

I have a type that encapsulates a Location so that it can be encoded and decoded in order to be persisted by UserDefaults. However, I have not created an encapsulating type for encoding and decoding Address.

My question is: Since I want to persist a Location, which contains an Address, do I need to create the encapsulating type to encode and decode an Address as well, or would it be more appropriate to just encode and decode the Address properties inside of the Location when I encode and decode its other properties?

I don't know in advance if Address will be applied to other types as a property that may need persisted in UserDefaults. I am leaning toward creating an encapsulating type to encode and decode Address.


Solution

  • It appears that I should create an encapsulating type to ensure that the address property of my Location instance can be encoded and decoded. That will allow me to simply call coder.encode(address, forKey: "address").

    I found a helpful answer after changing my search query terms.