Search code examples
typesswiftoption-typetype-variables

Defining Swift functions that operate on Types instead of values


In Swift, the ? operator takes Types as parameters, instead of values:

var z = 42? // won't create an Optional<Int> and won't compile
var z : Int? = 42 // ? takes Int and give a Optional<Int>

How can I create my own functions, or operators that work on Type instead of values?


Solution

  • What you want to achieve is not possible.

    However there is a workaround: you can create a custom operator that given a literal or variable, converts it to an optional. Swift doesn't allow using the ? character in custom operators, I am choosing a random combination, but feel free to use your own:

    postfix operator >! {}
    
    postfix func >! <T>(value: T) -> T? {
        return value as T?
    }
    

    Once done, you can use it as follows (output from playground):

    10>! // {Some 10}
    
    "Test">! // {Some "Test"}