像往常一樣栅隐,用字符串當(dāng)key
缺點(diǎn):
- 容易拼寫錯(cuò)誤
- 重復(fù)定義
- 多人開發(fā)項(xiàng)目,難于管理
eg:
import Foundation
import UIKit
protocol UserDefaultNameSpace {}
extension UserDefaultNameSpace {
static func namespace<T>(_ key:T) -> String where T: RawRepresentable {
return "\(Self.self).\(key.rawValue)"
}
}
protocol UserDefaultSettable: UserDefaultNameSpace {
associatedtype UserDafaultKey: RawRepresentable
}
extension UserDefaultSettable where UserDafaultKey.RawValue == String {}
extension UserDefaultSettable {
/// 關(guān)于 Int 類型的存儲(chǔ)和讀取
static func set(value: Int, forKey key: UserDafaultKey) {
let key = namespace(key)
UserDefaults.standard.set(value, forKey: key)
}
static func integer(value: Int, forKey key: UserDafaultKey) {
let key = namespace(key)
UserDefaults.standard.integer(forKey: key)
}
/// 關(guān)于 String 類型存儲(chǔ)和讀取
static func set(value: Any?, forKey key: UserDafaultKey) {
let key = namespace(key)
UserDefaults.standard.set(value, forKey: key)
}
static func string(value: Any?, forKey key: UserDafaultKey) {
let key = namespace(key)
UserDefaults.standard.string(forKey: key)
}
}
// MARK: - 使用方式
extension UserDefaults {
struct Account: UserDefaultSettable {
enum UserDafaultKey: String {
case name
case age
case birth
}
}
}
class test {
func testFunction() {
UserDefaults.Account.set(value: 20, forKey: .age)
UserDefaults.Account.set(value: "hjq", forKey: .name)
}
}