함수를 인자로 받거나 결과로 반환하는 함수
map 함수는 컨테이너가 갖고 있던 요소들을 매개변수를 통해 받은 함수를 통해 변형(transform)하여 새로운 컨테이너를 생성해서 반환한다.
✅ Apple Developer 공식 홈페이지에서 map 함수는 아래와 같이 정의되어 있다.
func map<T>(_ transform: (Self.Element) throws -> T) rethrows -> [T]
다음은 map함수를 사용해서 [1, 2, 3, 4, 5]인 배열의 각 요소에 2를 곱한 새로운 배열을 얻어 출력해보는 예제이다.
let array : [Int] = [1,2,3,4,5]
let myArray : [Int] = array.map( { (element: Int) -> Int in
return element * 2 } )
print("\(multipliedArray)") // [2,4,6,8,10]
클로저의 축약 문법을 사용하면 아래처럼 간단하게도 나타낼 수 있다.
let array : [Int] = [1,2,3,4,5]
let myArray : [Int] = array.map { $0 * 2 }
print("\(multipliedArray)") // [2,4,6,8,10]
filter 함수는 반환 타입이 Bool인 매개변수 함수의 결과가 true이면 새로운 컨테이너를 생성해서 해당 값을 담아 반환한다.
✅ Apple Developer 공식 홈페이지에서 filter 함수는 아래와 같이 정의되어 있다.
func filter(_ isIncluded: (Self.Element) throws -> Bool) rethrows -> [Self.Element]
다음은 filter함수를 사용해서 [1, 2, 3, 4, 5]인 배열의 각 요소에서 짝수에 해당하는 값들을 갖는 새로운 배열을 얻어 출력해보는 예제이다.
let array : [Int] = [1,2,3,4,5]
let myArray : [Int] = array.filter { (element) -> Bool in
return element % 2 == 0
}
print("\(myArray)") // [2,4]
클로저의 축약 문법을 사용하면 아래처럼 간단하게도 나타낼 수 있다.
let array : [Int] = [1,2,3,4,5]
let myArray : [Int] = array.filter { $0 % 2 == 0 }
> print("\(myArray)") // [2,4,6,8,10]
reduce 함수는 주어진 클로저를 사용하여 컨테이너의 요소를 결합한 결과를 반환한다.
✅ Apple Developer 공식 홈페이지에서 reduce 함수는 아래와 같이 정의되어 있다.
func reduce<Result>(
_ initialResult: Result,
_ nextPartialResult: (Result, Self.Element) throws -> Result
) rethrows -> Result
다음은 reduce함수를 사용해서 [1, 2, 3, 4, 5]인 배열의 각 요소를 더한 값을 sum이라는 변수에 담아 출력해보는예제이다.
let array : [Int] = [1,2,3,4,5]
let sum : Int = array.reduce(0, { (first: Int, second: Int) -> Int in
return first + second
})
print("\(sum)") // 15
클로저의 축약 문법을 사용하면 아래처럼 간단하게도 나타낼 수 있다.
let array : [Int] = [1,2,3,4,5]
let sum : Int = array.reduce(0) { $0 + $1 }
print("\(sum)") // 15
잘못된 내용이 있다면 언제든지 댓글로 알려주시면 감사하겠습니다!