propertyWrapper

属性包装类

Posted by Genie on July 17, 2020

通过包装类可以大大减少的code 量 首先通过UserDefaults 来看下

  1. enums 创建keys
1
2
3
4
5
extension UserDefaults {
    enum Keys {
        static let isFirstLaunch = "isFirstLaunch"
    }
  }
  1. 建立包装类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@propertyWrapper
struct UserDefaultWrapper<T> {
    private let key: String
    private let defaultValue: T

    init(key: String, defaultValue: T) {
        self.key = key
        self.defaultValue = defaultValue
    }

    var wrappedValue: T {
        get {
            UserDefaults.standard.object(forKey: key) as? T ?? defaultValue
        }
        set {
            UserDefaults.standard.set(newValue, forKey: key)
        }
    }
}
  1. 可以通过manage管理
1
2
3
4
5
class UserDefaultsManage {
    @UserDefaultWrapper(key: UserDefaults.Keys.isFirstLaunch, defaultValue: false)
    var isFirstLaunch: Bool
}

  1. 调用
1
2
3
4
5
6
7
8
9
10
11
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        let value = UserDefaultWrapper(key: UserDefaults.Keys.isFirstLaunch, defaultValue: true)
        print(value.wrappedValue)

        print(UserDefaultsManage().isFirstLaunch)
    }
}

参考:

https://nshipster.com/propertywrapper/