Reputation:
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
?
Upvotes: 3
Views: 112
Reputation: 154543
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!)
}
Upvotes: 2