Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@dineshba
Last active May 30, 2018 11:49
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 dineshba/45a1815d29b677b6ef39a31631c14eac to your computer and use it in GitHub Desktop.
Save dineshba/45a1815d29b677b6ef39a31631c14eac to your computer and use it in GitHub Desktop.
struct ComputerLab { // Computer Lab contains list of laptops.
let laptops: [Laptop]
}
// we want to get the list of mac laptops
// Traditional way
var macLaptops: [Laptop] = []
for laptop in computerLab.laptops {
if laptop.name.contains("Mac") {
macLaptops.append(laptop)
}
}
// Swifty way or Functional way
// filter is an higher order function which takes the predicate
// and gives the subset which satisfies the predicate.
let macLaptops = computerLab.laptops.filter { (laptop: Laptop) -> Bool in
return laptop.name.contains("Mac")
}
// Simplificaton 1: Types can be inferred. So we can remove types
let macLaptops = computerLab.laptops.filter { laptop in
return laptop.name.contains("Mac")
}
// Simplificaton 2: If there is one line function, return is optional
let macLaptops = computerLab.laptops.filter { laptop in laptop.name.contains("Mac") }
// Simplificaton 3: Shorthand argument names. $0 for first argument.
let macLaptops = computerLab.laptops.filter { $0.name.contains("Mac") }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment