Search

Swift - 일급 객체 [ First-Class Citizen ]

Tag
정보공유
Tech
Swift
날짜
2023/10/22
작성자
이창준
해결

일급 객체 - First-Class Citizen

Swift 는 함수형 프로그램.. Swift 에서, 클로저 / 함수 는 일급 객체로 취급이 된다.

일급 객체의 조건

1.
객체가 런타임에도 생성 가능
2.
객체를 인자 값으로 전달 가능
3.
객체를 반환 값으로 사용 가능
4.
데이터 구조 안에 저장 가능

⇒ 다시 정리

1. 변수에 할당

let add: (Int, Int) -> Int = { (a, b) in return a + b }
Swift
복사

2. 인자 값으로 전달

func applyOperation(_ operation: (Int, Int) -> Int, a: Int, b: Int) -> Int { return operation(a, b) } let result = applyOperation(add, a: 5, b: 3)
Swift
복사

3. 반환 값으로 사용

func getAdd() -> (Int, Int) -> Int { return { (a, b) in return a + b } } let addFunction = getAdd() let result = addFunction(5, 3)
Swift
복사

4. 자료 구조에 저장

var mathOperations: [(Int, Int) -> Int] = [] mathOperations.append(add) mathOperations.append({ (a, b) in return a - b }) for operation in mathOperations { let result = operation(5, 3) print(result) }
Swift
복사