Last active
May 30, 2018 11:49
-
-
Save dineshba/45a1815d29b677b6ef39a31631c14eac to your computer and use it in GitHub Desktop.
This file contains 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
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