Last active
August 29, 2015 14:13
-
-
Save MarkQSchultz/5d87c63c766d4a8229ca to your computer and use it in GitHub Desktop.
Optional unwrapping by condition (filter?) in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Optional { | |
// Will return the value of optional if it is not nil and if the function `condition` evaluates to true. | |
// Otherwise, returns nil | |
func filter(condition: T -> Bool) -> T? { | |
if let x = self { | |
if condition(x) { | |
return x | |
} | |
} | |
return nil | |
} | |
} | |
// Usage | |
let x: Int? = 5 | |
let y = x.filter{ $0 == 5 } | |
// in if let | |
// evaluate to true | |
if let z = x.filter({ $0 == 5 }) { | |
// This code will execute. z will be set to 5. | |
} | |
if let z = x.filter({ value in value == 5 }) { | |
// This code will execute. z will be set to 5. | |
} else { | |
// This code will not execute | |
} | |
if let z = x.filter({ value in value != nil }) { | |
// This code will execute. z will be set to 5. | |
} else { | |
// This code will not execute | |
} | |
// evaluate to false | |
if let z = x.filter({ $0 == 7 }) { | |
// This code will not execute | |
} else { | |
// This code will execute since x is not equal to 7 | |
} | |
if let z = x.filter({ $0 == nil }) { | |
// This code will not execute | |
} else { | |
// This code will execute since x is not equal to 7 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment