UserDefaults using subscript which accepts enum or so.
// ios_userdefaults_sampleTests.swift
let expectedDate = Date()
userDefaults[.lastLaunchDate] = expectedDate
let date: Date? = userDefaults[.lastLaunchDate]
No typo😄
You can save any class conforming NSCoding.
class Team: NSObject, NSCoding {
var name = String()
override init() {}
required init?(coder aDecoder: NSCoder) {
name = aDecoder.decodeObject(forKey: "name") as! String
}
func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: "name")
}
}
let team = Team()
let teamName = "あんこう"
team.name = teamName
let userDefaults = UserDefaults.standard
userDefaults.archive(key: "team", value: team)
let value: Team? = userDefaults.unarchive(key: "team")
print(value!.name) // "あんこう"
- Swift4
- Xcode9.3
Swift 4 で UserDefaults を簡単に扱う - ユニファ開発者ブログ
swift-evolution/0148-generic-subscripts.md at master · apple/swift-evolution