nullswift5strong-typing

How do you write a typed nil in Swift?


I have a situation where I have to return a typed nil.

The only way I know of to "make" a typed nil is ..

// need to return String nil
var x: String? = nil
return x

..
// need to return Thing nil
var x: Thing? = nil
return x

is there a simpler way to write that?


Solution

  • Optional is just an enum with 2 cases

    enum Optional<Wrapped> {
        case some(Wrapped)
        case none
    }
    

    nil is just syntactic sugar for the none case. To explicitly specify the type of a nil, you can just access the none case in the same way as any other enum.

    Optional<String>.none
    

    String? is sugar for Optional<String>, so this can be even shorter:

    String?.none
    

    The as operator can also specify the target type for nil, so

    nil as String?
    

    is yet another way.