๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
iOS ๐ŸŽ/Swift

Swift - ๊ณ ์ฐจํ•จ์ˆ˜, Higher-order function

by yongmin.Lee 2021. 2. 10.

๊ณ ์ฐจํ•จ์ˆ˜

  • ๊ณ ์ฐจํ•จ์ˆ˜(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

 

'iOS ๐ŸŽ > Swift' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

Method Dispatch  (0) 2021.12.06
KVO, Key-Value Observing  (0) 2021.12.06
Swift19 - ์ต์Šคํ…์…˜  (0) 2021.02.10
Swift18 - ํ”„๋กœํ† ์ฝœ  (0) 2021.02.10
Swift17 - assert/guard  (0) 2021.02.10