Swift
Swift - first class object(1급 객체)
leebean
2021. 10. 9. 15:25
(인덕대학교 컴퓨터소프트웨어학과 iOS프로그래밍기초(21-2학기)한성현 교수님 강의 내용을 변형 및 요약 했습니다.)
first class object(1급 객체)
- 사용할 때 다른 요소들과 아무런 차별이 없다는 의미를 가집니다.
- 아래의 조건을 만족하면 1급 객체라고 말할 수 있습니다.
- 함수를 매개변수로 사용이 가능해야 합니다.
- 함수를 리턴값으로 사용해야 합니다.
- 함수를 변수에 저장이 가능해야 합니다.
(1급 객체 예제)
//일급 객체 의 조건이 모두 들어있는 코드
func plus (num1 :Int )->Int {
return num1 +1
}
func miner (num2 :Int )->Int {
return num2 -1
}
let secondPlus = plus // 함수를 자료형 처럼 사용됩니다.
let secondMiner = miner // 함수를 자료형 처럼 사용됩니다.
print (plus (num1 :10 ))
print (secondPlus (10 ))
func plusminer (num3 :(Int )->Int , value :Int ){
let result = num3 (value )
//num3에 저장된 secondPlus, secondMiner변수가 저장되어있고
//그 값을 result에 저장합니다.
print ("result = \(result)")
}
plusminer(num3 :secondPlus , value :10 )//secondPlus(10)
//변수 secondPlus는 지금 Plus함수에 저장되어 있습니다.
plusminer(num3 :secondMiner , value :10 )//secondMiner(10)
func deplusminer (updown :Bool )->(Int )->Int {
if updown {
return secondPlus//함수를 리턴하였습니다.
}
else {
return secondMiner
}
}
let show = deplusminer (updown :true )// let show = secondPlus
print (type (of :show ))// (Int) -> Int
print (show (10 ))// secondPlus(10)