Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 연산자
- continue
- 스파르타코딩캠프
- 프로그래머스 n의 배수 고르기
- 프로그래머스 n번째 원소까지
- 프로그래머스 최댓값 만들기(2)
- 프로그래머스 자동커밋
- 주사위 게임1
- 프로그래머스 문자열 정렬하기 (1)
- 스파르타 코딩클럽 내일배움캠프
- ruby설치
- 프로그래머스 조건에 맞게 수열 변경하기 3
- Break
- 문자열 붙여서 출력하기
- 프로그래머스 주사위 게임1
- array
- 객체지향
- 프로그래머스 배열 만들기1
- n번째 원소까지
- 문자열 정렬하기 (1)
- 프로그래머스
- 배열 만들기1
- Error installing cocoapods
- swift
- 조건에 맞게 수열 변경하기 3
- 프로그래머스 암호 해독
- cocoapods 설치 오류
- Til
- 스페인어
- 프로그래머스 문자열 붙여서 출력하기
Archives
- Today
- Total
dev._.note
[Swift] 고차함수(Higher-order Function) 본문
고차함수
고차함수란?
다른함수를 전달인자로 받거나 함수실행의 결과를 함수로 반환하는 함수
고차함수의 종류
- map
- filter
- reduce
- forEach
- compactMap
- FlatMap
map
선언 (Declaration)
func map<T>(_ transform: (Element) throws -> T) rethrows -> [T]
매개변수 (Parameters)
transform
- 매핑 클로저로 이 컨테이너의 요소를 매개변수로 받아들이고 정의한 클로저의 형태에 맞게 변환된 값을 반환.
리턴타입 (Return Value)
- 변환된 요소를 포함하는 배열 반환
예시 (String배열 > Int배열)
let string = ["1", "2", "3", "4", "5"]
let numbers = string.map { Int($0)! }
print(numbers)
// [1, 2, 3, 4, 5]
예시 (int배열 > 연산 후 변환된 Int배열)
// numbers의 각 요소에 9 곱하기
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
let multiplyArray: [Int] = numbers.map { $0 * 9 }
print(multiplyArray)
// [9, 18, 27, 36, 45, 54, 63, 72, 81]
filter
선언 (Declaration)
func filter(_ isIncluded: (Self.Element) throws -> Bool) rethrows -> [Self.Element]
매개변수 (Parameters)
isIncluded
- 컨테이너의 요소를 인수로 취하고, 요소가 반환된 배열에 포함되어야 하는지 여부를 Bool 값으로 반환하는 클로저
리턴타입 (Return Value)
- inIncluded에 맞게 true로 반환되는 값만 리턴
예시 (Int배열에서 짝수만 호출)
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
let evenNumbers = numbers.filter { $0 % 2 == 0 }
print(evenNumbers)
// [2, 4, 6, 8]
예시 (String배열에서 2글자인 String만 추출하여 String배열 호출)
let animal = ["하마", "고양이", "개", "기린", "타조", "코끼리"]
let animals: [String] = animal.filter { $0.count == 2 }
print(animals)
// ["하마", "기린", "타조"]
reduce
선언 (Declaration)
func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result
매개변수 (Parameters)
initialResult
- 초기값으로 사용할 값을 넣으면 클로저가 처음 실행될 때, nextPartialResult에 전달.
nextPartialResult
- 새로운 누적 값으로 결합하는 클로저
리턴타입 (Return Value)
- 최종 누적 값이 반환. 요소가 없다면 intialResult값 반환.
예시 (Int배열 요소의 합)
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let sum = numbers.reduce(0, +)
print(sum)
// 55
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let sum = numbers.reduce(0) { $0 + $1 }
print(sum)
// 55
예시 (Int배열 요소의 곱하기)
let numbers = [1, 2, 3, 4, 5]
let sum = numbers.reduce(1, *)
print(sum)
// 120
let numbers = [1, 2, 3, 4, 5]
let sum = numbers.reduce(1) { $0 * $1 }
print(sum)
// 120
'Dev > SWIFT' 카테고리의 다른 글
[Swift] enumerated() 배열의 인덱스 가져오기 (0) | 2023.10.26 |
---|---|
[Swift] zip 함수 (0) | 2023.10.26 |
[Swift] reverse() 와 reversed()의 차이점 (1) | 2023.10.25 |
[Swift] Int형 정수 (0) | 2023.10.25 |
[Swift] Array(배열) 기초문법 (0) | 2023.10.25 |