Skip to content

Instantly share code, notes, and snippets.

@vukcevich
Created September 6, 2017 19:16
Show Gist options
  • Select an option

  • Save vukcevich/575b6cab40e9bacb8363755b4a615560 to your computer and use it in GitHub Desktop.

Select an option

Save vukcevich/575b6cab40e9bacb8363755b4a615560 to your computer and use it in GitHub Desktop.
Swift -- map / filter / reduce / flatMap functions - how to write shorter version - good reference point
//: Playground - noun: a place where people can play
import UIKit
//Swift --- Map -- Filter --- Reduce --- FlatMap
//An example how to write these functions in shorter form:
var HPs = [50, 60, 70]
//MAP
HPs.map( { (HP: Int) -> Int in
return HP + 10
})
HPs.map({ (HP: Int) in
return HP + 10
})
HPs.map({ HP in
return HP + 10
})
HPs.map({ HP in
HP + 10
})
HPs.map({ $0 + 10 })
HPs.map { $0 + 10 }
//Filter
var ages = [2, 4, 6, 8, 10]
let a0 = ages.filter( { (age: Int) -> Bool in return age < 5 } )
print("a0:", a0)
let a1 = ages.filter( { (age: Int) in return age < 5 } )
print("a1:",a1)
let a2 = ages.filter( { age in return age < 5 } )
print("a2:",a2)
let a3 = ages.filter( { age in age < 5 } )
print("a3:",a3)
let a4 = ages.filter( { $0 < 5 } )
print("a4:",a4)
let a5 = ages.filter { $0 < 5 }
print("a5:",a5)
//Reduce
var weights = [100, 200, 300, 400, 500]
let w0 = weights.reduce(0, { (result: (Int, Int)) -> Int in
return result.0 + result.1
})
print("w0:",w0)
let w1 = weights.reduce(0, { result -> Int in
return result.0 + result.1
})
print("w1:", w1)
let w2 = weights.reduce(0, { result in
return result.0 + result.1
})
print("w2:", w2)
let w3 = weights.reduce(0, { result in
result.0 + result.1
})
print("w3:", w3)
let w4 = weights.reduce(0, { $0 + $1 })
print("w4:", w4)
let w5 = weights.reduce(0, +)
print("w5:", w5)
//FlatMap
let nestedArray = [[1,2,3], [4,5,6]]
let flattenedArray = nestedArray.flatMap { $0 }
flattenedArray // [1, 2, 3, 4, 5, 6]
let nestedArray2 = [[1,2,3], [4,5,6]]
var multipliedFlattenedArray = nestedArray2.flatMap { $0.map
{ $0 * 2 }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment