Let's say I have the following:
var didConnectObserver: NSObjectProtocol?
didConnectObserver = NSNotificationCenter.defaultCenter().addObserverForName(
MyKey, object: nil, queue: nil, usingBlock: { (note) -> Void in
...
})
At some point I unregister:
NSNotificationCenter.defaultCenter().removeObserver(didConnectObserver)
This doesn't work, though, because didConnectObserver is an optional. Is there a more compact way to write this than:
if let obs = didConnectObserver {
NSNotificationCenter.defaultCenter().removeObserver(obs)
}
that still does the right thing if didConnectObserver is nil?
I'm still getting the hang of map with Optionals, but I believe this will work:
_ = didConnectObserver.map(NSNotificationCenter.defaultCenter().removeObserver)
If didConnectObserver is nil, the result of this is nil, otherwise it executes the function with didConnectObserver!. The _ = is necessary to suppress a warning Result of call to 'map' is unused.
Here's what autocomplete shows when you type didConnectObserver.map:

Here is another example of the same concept:
func add5(i: Int) {
print("add 5 called")
print(i + 5)
}
let a: Int? = 10
_ = a.map(add5)
If a is nil, then add5 is not called. If a is Optional(10), then add5 is called and 15 is printed.
It works just like:
if a != nil {
add5(a!)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With