iOS ๐/Swift
Swift - ๊ณ ์ฐจํจ์, Higher-order function
yongmin.Lee
2021. 2. 10. 16:18
๊ณ ์ฐจํจ์
- ๊ณ ์ฐจํจ์(Higher-order function) : ‘๋ค๋ฅธ ํจ์๋ฅผ ์ ๋ฌ์ธ์๋ก ๋ฐ๊ฑฐ๋ ํจ์์คํ์ ๊ฒฐ๊ณผ๋ฅผ ํจ์๋ก ๋ฐํํ๋ ํจ์’๋ฅผ ๋ปํ๋ค.
- ์ค์ํํธ์ ํจ์(ํด๋ก์ )๋ ์ผ๊ธ์๋ฏผ์ด๊ธฐ ๋๋ฌธ์ ํจ์์ ์ ๋ฌ์ธ์๋ก ์ ๋ฌํ ์ ์๊ณ ํจ์์ ๊ฒฐ๊ณผ๊ฐ์ผ๋ก ๋ฐํํ ์ ์์ผ๋ฏ๋ก, ๊ณ ์ฐจํจ์์ด๋ค
์ค์ํํธ ํ์ค๋ผ์ด๋ธ๋ฌ๋ฆฌ์์ ์ ๊ณตํ๋ ์ ์ฉํ ๊ณ ์ฐจํจ์
1. map
mapํจ์๋ ์ปจํ ์ด๋ ๋ด๋ถ์ ๊ธฐ์กด ๋ฐ์ดํฐ๋ฅผ ๋ณํ(transform)ํ์ฌ ์๋ก์ด ์ปจํ ์ด๋๋ฅผ ์์ฑ
let numbers: [Int] = [0, 1, 2, 3, 4]
var doubledNumbers = numbers.map({ (number: Int) -> Int in
return number * 2
})
print(doubledNumbers) // [0, 2, 4, 6, 8]
2. flatMap
flatMap์ ์ปจํ ์ด๋ ๊ฐ๊ฐ ์๋ฆฌ๋จผํธ๋ค์ ๋ณํ ๊ฒฐ๊ณผ๋ฅผ ํฉ์น ํ๋์ ์ผ์ฐจ ๋ฐฐ์ด์ ์์ฑ
let numbers = [1, 2, 3, 4]
let mapped = numbers.map { Array(repeating: $0, count: $0) }
// [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
let flatMapped = numbers.flatMap { Array(repeating: $0, count: $0) }
// [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
3. compactMap
compactMap์ ์ปจํ ์ด๋์ ๋ณํ๊ฒฐ๊ณผ๊ฐ nil์ธ ๊ฒฝ์ฐ๋ฅผ ์ ์ธํ๊ณ ์๋ก์ด ์ปจํ ์ด๋ ์์ฑ
let possibleNumbers = ["1", "2", "three", "///4///", "5"]
let mapped: [Int?] = possibleNumbers.map { str in Int(str) }
// [1, 2, nil, nil, 5]
let compactMapped: [Int] = possibleNumbers.compactMap { str in Int(str) }
// [1, 2, 5]
4. filter
filterํจ์๋ ์ปจํ ์ด๋ ๋ด๋ถ์ ๊ฐ์ ๊ฑธ๋ฌ์ ์๋ก์ด ์ปจํ ์ด๋๋ก ์ถ์ถ
let numbers: [Int] = [0, 1, 2, 3, 4]
// ๋งค๊ฐ๋ณ์, ๋ฐํ ํ์
, ๋ฐํ ํค์๋(return) ์๋ต, ํํ ํด๋ก์
let oddNumbers: [Int] = numbers.filter {
$0 % 2 != 0
}
print(oddNumbers) // [1, 3]
5. reduce
reduceํจ์๋ ์ปจํ ์ด๋ ๋ด๋ถ์ ์ฝํ ์ธ ๋ฅผ ํ๋๋ก ํตํฉ
let someNumbers: [Int] = [2, 8, 15]
// ์ด๊น๊ฐ์ด 3์ด๊ณ someNumbers ๋ด๋ถ์ ๋ชจ๋ ๊ฐ์ ๋ํฉ๋๋ค.
let sumFromThree = someNumbers.reduce(3) { $0 + $1 }
print(sumFromThree) // 28