Sequence
, Collection
ํ๋กํ ์ฝ์ ๋ฐ๋ฅด๋ ํ์
, Optional
์ ๋ชจ๋ map ์ ์ฌ์ฉํ ์ ์๋ค.for - in
๊ตฌ๋ฌธ์ผ๋ก๋ map
์ผ๋ก ์์ฑํ ๊ตฌ๋ฌธ์ ์ถฉ๋ถํ ์์ฑํ ์ ์๋ค.container.map(f(x)) -> return f(container ์ ๊ฐ ์์)
let arr = ["ํ์ฐ", "์จ๋", "ํฐํ๋", "ํจ์ฐ", "์ ๋ฆฌ", "์์", "์ค์", "์ํ"]
let heartArr = arr.map { $0 + "โค" }
// ["ํ์ฐโค", "์จ๋โค", "ํฐํ๋โค", "ํจ์ฐโค", "์ ๋ฆฌโค", "์์โค", "์ค์โค", "์ํโค"]
Bool
let three = arr.filter { $0.length == 3 } // ["ํฐํ๋"]
Swift ์์
public func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result
nextPartialResult: (Result // ์ด๊น๊ฐ or ์ด์ ๊ฒฐ๊ณผ, Element // ํ์ฌ ๋ํ ์์)
let numbers: [Int] = [1, 2, 3, 4]
var sum: Int = numbers.reduce(0, { (result: Int, next: Int) -> Int in
return result + next
})
var sum: Int = numbers.reduce(0) { $0 + $1 }
public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Element) throws -> ()) rethrows -> Result
var sum: Int = numbers.reduce(into: 0) { $0 + $1 } // ํด๋ก์ ๊ฐ ๋ฐํํด์ ๊ฐ์ ์ ๋ฌํ์ง ์๊ณ ํด๋น ๊ฐ์ ๊ณ์ ๋ฐ๊พธ์ด๊ฐ๋ค.
// map + filter ์ฒ๋ผ ์ฌ์ฉ
// [] ์ ์ง์๋ง ๊ฑธ๋ฌ๋ด์ 2๋ฐฐํด์ append
var doubledNumbers: [Int] = numbers.reduce(into: []) { (result: inout [Int], next: Int) in
guard next % 2 == 0 else { return }
result.append(next * 2)
}
์ผ๊ณฐ์ ์ค์ํํธ5 ํ๋ก๊ทธ๋๋ฐ