Swift, Higher-order function

iDOΒ·2021λ…„ 10μ›” 5일
1

Swift

λͺ©λ‘ 보기
4/5
post-thumbnail

🍁 map(:), filter(:), reduce(_:)

map(_:)

λ°°μ—΄ μš”μ†Œλ“€μ„ 쑰건에 따라 μƒˆλ‘­κ²Œ κ΅¬μ„±ν•˜λŠ” λ©”μ†Œλ“œμž…λ‹ˆλ‹€

let cast = ["Do", "Young", "Mac"]
let lowercaseNames = cast.map { $0.lowercased() } // ["do", "young", "mac"] 
let letterCounts = cast.map { $0.count } // [2, 5, 3]

filter(_:)

λ°°μ—΄ μš”μ†Œ 쀑 쑰건에 따라 κ±°λ₯΄λŠ” λ©”μ†Œλ“œμž…λ‹ˆλ‹€.

let num = [1, 2, 3, 4, 5, 6, 7]
let evenNum = num.filter{ $0 % 2 == 0 } // [2, 4, 6]

reduce(_:)

λ°°μ—΄μ˜ μš”μ†Œλ“€μ„ ν•˜λ‚˜μ˜ κ°’μœΌλ‘œ λ§Œλ“œλŠ” λ©”μ†Œλ“œμž…λ‹ˆλ‹€.

let numbers = [1, 2, 3, 4]
let numbersSum = num.reduce(0) { $0 + $1 } // numberSum == 10
profile
이곳은 μ €λ₯Ό μœ„ν•œ iOS μ„€λͺ…μ„œμž…λ‹ˆλ‹€.

0개의 λŒ“κΈ€

κ΄€λ ¨ μ±„μš© 정보

Powered by GraphCDN, the GraphQL CDN