Search code examples
iosswiftoptional-values

What's the difference between testing an optional for "nil" and ".None"?


I see everywhere in swift language, people testing for optional values with if statements so they can safely force unwrap, in 2 ways:

if optionalValue != .None {   

... some code ...

}

or

if optionalValue != nil {   

... some code ...

}

What's the difference and can it somehow influence my app/code in any way? What's better?


Solution

  • In normal usage there's no difference, they are interchangeable. .None is an enum representation of the nil (absence of) value implemented by the Optional<T> enum.

    The equivalence of .None and nil is thanks to the Optional<T> type implementing the NilLiteralConvertible protocol, and an overload of the != and == operators.

    You can implement that protocol in your own classes/structs/enums if you want nil to be assignable, such as:

    struct MyStruct : NilLiteralConvertible {
        static func convertFromNilLiteral() -> MyStruct {
            return MyStruct() // <== here you should provide your own implementation
        }
    }
    
    var t: MyStruct = nil
    

    (note that the variable is not declared as optional)