Notice
Recent Posts
Link
«   2025/04   »
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 29 30
Archives
관리 메뉴

도슐랭스타

iOS - first class object, first class citizen(1급 객체, 1급 시민) 본문

iOS

iOS - first class object, first class citizen(1급 객체, 1급 시민)

도도.__. 2024. 10. 14. 20:53

일급 객체

func up(num: Int) -> Int {
    return num + 1
}
func down(num: Int) -> Int {
    return num - 1
}
let toUp = up //1. 변수에 저장할 수 있다.
print(up(num:10))
print(toUp(10))
let toDown = down 

func upDown(Fun: (Int) -> Int, value: Int) { //매개변수로 전달할 수 있다.
    let result = Fun(value)
    print("결과 = \(result)")
}
upDown(Fun:toUp, value: 10) //toUp(10)
upDown(Fun:toDown, value: 10) //toDown(10)

func decideFun(x: Bool) -> (Int) -> Int { //리턴값으로 사용할 수 있다.
//매개변수형 리턴형이 함수형임.
if x {
    return toUp
} else {
    return toDown
}
}
let r = decideFun(x:true) // let r = toUp
print(type(of:r)) //(Int) -> Int
print(r(10)) // toUp(10)

다음 조건을 충족하는 객체를 1급 객체라고 함.

  1. 변수에 저장할 수 있다.
  2. 매개변수로 전달할 수 있다.
  3. 리턴값으로 사용할 수 있다.

클로저 표현식

{(<매개변수 이름>: <매개변수 타입>, … ) -> <반환 타입> in
	// 클로저 표현식 코드
}
let add1 = { (x: Int, y: Int) -> Int in
	return(x+y)
}
//print(add1(x:10, y:20)) //주의 error: extraneous(관련 없는) argument labels 'x:y:' in call
print(add1(10, 20)) //OK
print(type(of:add1))

클로저는 매개변수와 반환 타입을 지정하여 정의할 수 있음.
함수와 달리 호출할 때 매개변수 레이블을 사용하지 않음.

let multiply = {(val1: Int, val2: Int) -> Int in
    return val1 * val2
}// 여기서 multiply의 자료형은 (Int, Int) -> Int
let result = multiply(10, 20) //상수를 함수처럼 호출,200
print(result)

반응형

'iOS' 카테고리의 다른 글

iOS- 9주  (0) 2024.10.30
iOS - 클래스  (1) 2024.10.16
iOS - 함수(2)  (0) 2024.10.14
iOS - 함수(1)  (0) 2024.10.04
iOS - 연산자와 옵셔널  (1) 2024.09.25
Comments