Skip to content

Instantly share code, notes, and snippets.

@MarkQSchultz
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MarkQSchultz/5d87c63c766d4a8229ca to your computer and use it in GitHub Desktop.
Save MarkQSchultz/5d87c63c766d4a8229ca to your computer and use it in GitHub Desktop.
Optional unwrapping by condition (filter?) in Swift
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