what is ?(nil) means in function ?

Hi !


in this case ..


self.getMyCallback?(nil)


... what is ?(nil) means?

It's grouped this:


     (self.getMyCallback?)(nil)


That is, it means:


if self.getMyCallback != nil {
     self.getMyCallback! (nil) 
}


This is similar to what Swift calls "optional chaining".

Thanks for the answer : )


and would you plz tell me meaning of code below ?


self.getMyCallback! (nil)


do you mean self.getMyCallback! = (nil) , right ??

No, check out Quincey's post again. The 'nil' is a parameter to the callback function.


Another way to re-write the optional chaining:

if let theCallback = self.getMyCallback { // Side note: is your property named 'getMyCallback'; prob best to use 'myCallback'
   theCallback(nil)
}


Also, while there are exceptions, it's nice to have functions take named arguments. So if the callback function was declared as:

func callback(context aContext: AnyObject?)


Then it would be more obvious at the call-site as to what 'nil' is:

theCallback(context: nil)
Accepted Answer

Actually, what you said is not quite true in the current Swift. There are functions and there are closures, and we're talking about a closure here, not a function. So, perhaps there was something like this:


     var getMyCallback: ((Any?) -> Void)?


(that is a property whose value is an optional closure taking one parameter). Adding the "!" unwraps the optional, producing an actual closure, as you said. But when you invoke a closure, you are not allowed to use parameter keywords, since in Swift 3 keywords are not part of the closure type. The compiler will complain if you try to do this:


if let theCallback = self.getMyCallback {
   theCallback (context: nil) // incorrect, parameter label not allowed
}


The reason is that Swift 2 was ambiguous about whether a closure could be called with the "wrong" parameter labels. Because it's common for the labels to be irrelevant (especially for closures used as callbacks), Swift 3 outlaws labels when you invoke a closure.

Thanks for the clarifcation, Quincey; I hadn't thought about the closure case.

Thanks


rsharp and QuinceyMorris ! 😁

what is ?(nil) means in function ?
 
 
Q