Skip to content

Instantly share code, notes, and snippets.

@imjhk03
Created March 1, 2021 17:27
Show Gist options
  • Save imjhk03/7c11c541b2bc69ba75f558f90d00b48d to your computer and use it in GitHub Desktop.
Save imjhk03/7c11c541b2bc69ba75f558f90d00b48d to your computer and use it in GitHub Desktop.
A simple example of filter, map, reduce method
/*
Filter
*/
let familyNames = ["Park", "Lee", "Jong", "Kim", "Choi"]
let longFamilyNames = familyNames.filter { $0.count > 3 }
print(longFamilyNames)
// ["Park", "Jong", "Choi"]
let familyNames = ["Park", "Lee", "Jong", "Kim", "Choi"]
var longFamilyNames = [String]()
for familyName in familyNames {
if familyName.count > 3 {
longFamilyNames.append(familyName)
}
}
print(longFamilyNames)
// ["Park", "Jong", "Choi"]
/*
Map
*/
let prices: [Double] = [400, 350, 150, 225, 500]
let totalPricesWithTax = prices.map { $0 * 1.05 }
print(totalPricesWithTax)
// [420.0, 367.5, 157.5, 236.25, 525.0]
let prices: [Double] = [400, 350, 150, 225, 500]
var totalPricesWithTax = [Double]()
for price in prices {
totalPricesWithTax.append(price * 1.05)
}
print(totalPricesWithTax)
// [420.0, 367.5, 157.5, 236.25, 525.0]
/*
Reduce
*/
let prices: [Double] = [420.0, 367.5, 157.5, 236.25, 525.0]
let totalPrice = prices.reduce(0.0, +)
print(totalPrice)
// 1706.25
let prices: [Double] = [420.0, 367.5, 157.5, 236.25, 525.0]
var totalPrice: Double = 0
for price in prices {
totalPrice += price
}
print(totalPrice)
// 1706.25
let numbers = [1, 2, 3, 4]
let numberSum = numbers.reduce(0) { x, y in x + y }
print(numberSum)
// 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment