Swift对象中set、get理解

// 2
struct Cat: CustomStringConvertible {
    // 3
    var name: String? {
        // 4
        get {
            return UserDefaults.standard.string(forKey: "CatName")
        }

        // 5
        nonmutating set {
            if let newValue = newValue {
                UserDefaults.standard.set(newValue, forKey: "CatName")
            } else {
                UserDefaults.standard.removeObject(forKey: "CatName")
            }
        }
    }

    var description: String {
        return name ?? ""
    }
}

你可能感兴趣的:(Swift对象中set、get理解)