Created
March 1, 2021 17:27
-
-
Save imjhk03/7c11c541b2bc69ba75f558f90d00b48d to your computer and use it in GitHub Desktop.
A simple example of filter, map, reduce method
This file contains hidden or 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
/* | |
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