Swift随笔

三步走:使用Property Wrapper优化UserDefa

2020-11-30  本文已影响0人  CoderXLL

本次优化受到喵神使用 Property Wrapper 为 Codable 解码设定默认值的启发,不断地思考发现问题,不断地在现有基础上优化解决问题。特此感谢

一、成长期

1.调用方式
private let isAgreePrivacyKey = "isAgreePrivacy"
//1. 存缓存
UserDefaults(suiteName: "appUserSuite")!setValue(true, forKey: isAgreePrivacyKey)
//2. 取缓存
UserDefaults(suiteName: "appUserSuite")!.bool(forKey: isAgreePrivacyKey)
2.缺点

二、完全体

1.内部实现
final public class XLLDefaultsBox<T> {
    public var value: T {
        didSet {
            setterAction(value)
        }
    }
    
    public typealias SetterAction = (T) -> Void
    var setterAction: SetterAction
    
    public init(_ v: T, setterAction action: @escaping SetterAction) {
        value = v
        setterAction = action
    }
}

private let isAgreePrivacyKey = "isAgreePrivacy"
final public class XLLAppDefaults {
    static let appUser = UserDefaults(suiteName: "appUserSuite")

    public static var isAgreePrivacy: XLLDefaultsBox<Bool?> = {
        let isAgreePrivacy = appUser.bool(forKey: isAgreePrivacyKey)
        return XLLDefaultsBox<Bool?>(isAgreePrivacy) { isAgreePrivacy in
            appUser.set(isAgreePrivacy, forKey: isAgreePrivacyKey)
        }
    }()
}
2.调用方式
//1. 存缓存
XLLAppDefaults.isAgreePrivacy.value = true
//2. 取缓存
XLLAppDefaults.isAgreePrivacy.value
3. 优点
4. 缺点

三、究极体

1. 内部实现
extension UserDefaults {
    static var appUser: UserDefaults = UserDefaults(suiteName: "appUserSuite")!
}

@propertyWrapper
struct XLLAppDefaultsWrapper<T> {
    var key: String?
    var value: T
    
    var wrappedValue: T {
        get { value }
        set {
            value = newValue
            if let key = key {
                UserDefaults.appUser.setValue(newValue, forKey: key)
            }
        }
    }
    
    public init(_ initialValue: T, key: String) {
        value = initialValue
        self.key = key
    }
}

private let isAgreePrivacyKey = "isAgreePrivacy"
public class XLLAppDefaults {
    public static let shared = XLLAppDefaults()
    
    //注意,这里若非跨模块调用,权限关键词public可去除
    @XLLAppDefaultsWrapper<Bool>(UserDefaults.appUser.bool(forKey: isAgreePrivacyKey), key: isAgreePrivacyKey)
    public var isAgreePrivacy
}
2.调用方式
//存缓存
XLLAppDefaults.shared.isAgreePrivacy = false
//取缓存
XLLAppDefaults.shared.isAgreePrivacy
3.优点
上一篇下一篇

猜你喜欢

热点阅读