在 swift 中使用 @propertyWrapper 替代隐式解包可选

Alternative to implicitly unwrapped optional using @propertyWrapper in swift

我发现自己使用了很多隐式解包选项,当初始化注入不起作用或创建 mvvm 模块时,例如:

class TodoView: UIViewController {
    
    var viewModel: TodoViewModelProtocol!

}

不仅看起来不太好,而且总是强制解包也很痛苦如果我需要在显式解包的可选变量上使用 switch 语句 .

有什么方法可以摆脱隐式展开的可选,例如在 swift 5 中使用 @properyWrapper

您可以使用 属性 包装器模拟隐式解包选项,如下所示:

@propertyWrapper
struct MaybeUninitialized<T> {
    private var storage: T?
    var wrappedValue: T {
    get { storage! }
    set { storage = newValue}
    }
}

然后您甚至可以使用可能未初始化的字段来存储可选项,而不会意外地展开可选项。像这样:

@MaybeUninitialized var x: Int?

print(x) // will crash
x = nil
print(x) // print nil