在NSUserDefaults中存储嵌套对象

I'm trying to store custom codable struct with mutated property, but I'm always getting nil for that property.

例如,具有可编码的结构:

struct Test1: Codable {
    var testDate: Date? = nil
    let name: String
    let age: Int

    enum CodingKeys: String, CodingKey {
        case name
        case age
    }
}

with the following example JSON we will decode provided struct, and assign custom property testDate:

let json = """
{
"name": "test",
"age": 30,
}
"""


let jsonData = Data(json.utf8)
var test1 = try? JSONDecoder().decode(Test1.self, from: jsonData)
test1?.testDate = Date()

然后,我们将尝试将此结构存储在userDefaults中:

var currentTest: Test1? {
    get {
        let defaults = UserDefaults.standard
        guard let testData = defaults.object(forKey: "test1") as? Data,
            let test = try? PropertyListDecoder().decode(Test1.self,
                                                          from: testData) else {
            return nil
        }

        return test
    }
    set {
        let defaults = UserDefaults.standard
        defaults.set(try? PropertyListEncoder().encode(newValue), forKey: "test1")
    }
}

While this works for all of the codable properties, when I try to access a custom property, such as testDate I'm getting nil:

currentTest?.testDate = nil

有没有一种方法可以存储“嵌套”属性,而无需将它们作为单独的实例存储在UserDefautls中?

gist example - https://gist.github.com/ignotusverum/0cb9b57eef021eed3680530df519cedf