Why create “Implicitly Unwrapped Optionals”, since that implies you know there's a value?

前端 未结 10 1681
深忆病人
深忆病人 2020-11-22 07:30

Why would you create a \"Implicitly Unwrapped Optional\" vs creating just a regular variable or constant? If you know that it can be successfully unwrapped then why create a

10条回答
  •  北海茫月
    2020-11-22 07:53

    Implicitly unwrapped optionals are useful for presenting a property as non-optional when really it needs to be optional under the covers. This is often necessary for "tying the knot" between two related objects that each need a reference to the other. It makes sense when neither reference is actually optional, but one of them needs to be nil while the pair is being initialized.

    For example:

    // These classes are buddies that never go anywhere without each other
    class B {
        var name : String
        weak var myBuddyA : A!
        init(name : String) {
            self.name = name
        }
    }
    
    class A {
        var name : String
        var myBuddyB : B
        init(name : String) {
            self.name = name
            myBuddyB = B(name:"\(name)'s buddy B")
            myBuddyB.myBuddyA = self
        }
    }
    
    var a = A(name:"Big A")
    println(a.myBuddyB.name)   // prints "Big A's buddy B"
    

    Any B instance should always have a valid myBuddyA reference, so we don't want to make the user treat it as optional, but we need it to be optional so that we can construct a B before we have an A to refer to.

    HOWEVER! This sort of mutual reference requirement is often an indication of tight coupling and poor design. If you find yourself relying on implicitly unwrapped optionals you should probably consider refactoring to eliminate the cross-dependencies.

提交回复
热议问题