Search code examples
swiftmvvmdependency-injectionoption-typeproperty-wrapper

Alternative to implicitly unwrapped optional using @propertyWrapper in swift


I found myself using a lot of implicitly unwrapped optionals when initialiser injection would not work or when creating mvvm modules for examples:

class TodoView: UIViewController {
    
    var viewModel: TodoViewModelProtocol!

}

Not only it doesn't look so good, but its also a pain to always force unwrap if I need to use a switch statement on an explicitly unwrapped optional variable for example.

Is there any way to get rid of the implicitly unwrapped optional, for example using @properyWrapper in swift 5?


Solution

  • You can simulate implicitly unwrapped optionals with a property wrapper as follows:

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

    Then you can even use possibly uninitialized fields storing optionals without accidentially unwrapping the optional. Something like this:

    @MaybeUninitialized var x: Int?
    
    print(x) // will crash
    x = nil
    print(x) // print nil