[swift-users] Nil coalescing operator (??) and function vars

Peter Eddy peter.eddy at gmail.com
Mon Apr 18 13:42:17 CDT 2016


Hello,

I'd like to understand why I'm unable to use the nil coalescing operator
with functions.

For example, I'd like to write a function that takes an optional function
as a parameter and that uses the nil coalescing operator to select a
default function if the function's  function parameter is nil, e.g:

    func test(x: ((String) -> String)? = nil) {

      let qq = { (p:String) -> String in return "..." }

      let fn: String -> String = x ?? qq

      fn("test")
    }

When I do this the compiler complains that:

  Binary operator '??' cannot be applied to operands of type '((String) ->
String)?' and '(String) -> String:

In the Swift 2.2 Language Guide (
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/BasicOperators.html)
it states:

The nil coalescing operator is shorthand for the code below:

   1. a != nil ? a! : b

If I use the longhand option then the complier's fine:

    func test(x: ((String) -> String)? = nil)  {

        let qq = { (p:String) -> String in return "..." }

        let fn = x != nil ? x! : qq

        fn("test")
    }

So why doesn't the nil coalescing operator work for function vars?

thanks!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160418/9b0dcbc0/attachment.html>


More information about the swift-users mailing list