Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
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 31
Archives
Today
Total
관리 메뉴

브래의 슬기로운 코딩 생활

iOS프로그래밍 실무 4주차 정리 본문

2-1/iOS프로그래밍 실무

iOS프로그래밍 실무 4주차 정리

김브래 2023. 3. 29. 19:53

오늘은 가장 중요하다고 할 수 있는 1급 객체,1급 시민 /  클로저 / 생성자 등등을 복습했다.

 


1급 객체(first class object)  / 1급 시민(first class citizen)


1급 객체(first class object) 또는 1급 시민(first class citizen)

https://en.wikipedia.org/wiki/First-class_citizen

 

First-class citizen - Wikipedia

From Wikipedia, the free encyclopedia Concept in programming language design In programming language design, a first-class citizen (also type, object, entity, or value) in a given programming language is an entity which supports all the operations generall

en.wikipedia.org

Swift의 함수는 1급 객체이다.


다음 조건을 충족하는 객체를 1급 객체라고 한다.
1) 변수에 저장할 수 있다.
2) 매개변수로 전달할 수 있다.
3) 리턴값으로 사용할 수 있다.

first class object : (1)함수를 변수에 저장 가능

Swift는 함수를 데이터 타입처럼 처리할 수 있음

 

다음과 같이 함수를 상수 또는 변수에 할당하는 것이 가능
func inchesToFeet(inches: Float) -> Float {
    return inches * 0.0833333
}
let toFeet = inchesToFeet //함수를 자료형처럼 사용


함수를 호출하려면 원래의 함수 이름 대신에 상수 이름을 이용하여 호출 가능
print(inchesToFeet(inches:10)) 
print(toFeet(10)) //주의 : 호출시 매개변수명(num:) 안씀

 

first class object : (2) 함수를 매개변수로 사용

func inchesToFeet (inches: Float) -> Float {
    return inches * 0.0833333
}
let toFeet = inchesToFeet


위 함수는 Float형 매개변수, Float형 결과를 반환하기 때문에 함수의 데이터 타입(자료 형)
(Float) -> Float // (매개변수형) -> 리턴형

 

Int와 Double형을 매개변수로 받아서 String을 반환하는 함수의 데이터 타입
(Int, Double) -> String // (매개변수형, 매개변수형) -> 리턴형

 

매개변수로 함수를 받으려면, 함수를 받게 될 함수는 함수의 데이터 타입을 선언함
func outputConversion(converterFunc: (Float) -> Float, value: Float) {//함수를 매개변수로 사용
    let result = converterFunc(value) //toFeet(10)
    print("Result = \(result)")
}
outputConversion(converterFunc:toFeet, value: 10) // 피트로 변환하는 inchesToFeet함수 호출

 

first class object : (3) 함수를 리턴값으로 사용

func inchesToFeet (inches: Float) -> Float {
    return inches * 0.0833333
}

func inchesToYards (inches: Float) -> Float {
    return inches * 0.0277778
}
let toFeet = inchesToFeet
let toYards = inchesToYards

 

단위를 변환하고 콘솔에 결과를 출력하는 다른 함수
func outputConversion(converterFunc: (Float) -> Float, value: Float) { //함수를 매개변수로 사용
    let result = converterFunc(value)
    print("Result = \(result)")
}

 

outputConversion 함수를 호출할 때 선언된 데이터 타입과 일치하는 함수를 전달

 

매개변수로 적절한 변환 함수를 전달하면 인치를 피트 또는 야드로 변환하기 위하여 동일한 함수가 호출될 수 있음
outputConversion(converterFunc:toYards, value: 10) // 야드로 변환하는 inchesToYards함수 호출
outputConversion(converterFunc:toFeet, value: 10) // 피트로 변환하는 inchesToFeet함수 호출

 

반환 타입으로 함수의 타입을 선언하면 함수도 반환될 수 있음

 

다음 함수는 Boolean 매개변수의 값에 따라 toFeet 함수 또는 toYards 함수를 반환
func decideFunction (feet: Bool) -> (Float) -> Float { //매개변수형 리턴형이 함수형
    if feet {
        return toFeet //함수를 리턴
    } else {
        return toYards
    }
}

 

함수 : 일급 객체 실습

func up(num: Int) -> Int {
    return num + 1
}
func down(num: Int) -> Int {
    return num - 1
}

 

let toUp = up 
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)


클로저(Closure)


클로저 표현식

https://en.wikipedia.org/wiki/Closure_(computer_programming)

 

익명함수

 

C, C++, Objective-C의 block

 

Java의 Lambda function

 

C#의 Delegates

 

클로저 표현식은 독립적인 코드 블록
func add(x: Int, y: Int) -> Int {
    return(x+y)
}


print(add(x:10, y:20))
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))

 

클로저 표현식은 매개변수를 받거나, 값을 반환하도록 만들 수도 있음
{(<매개변수 이름>: <매개변수 타입>, … ) -> <반환 타입> in
    // 클로저 표현식 코드
}

 

두 개의 정수 매개변수를 받아서 곱한 값을 반환
let multiply = {(val1: Int, val2: Int) -> Int in // 매개변수 리턴형
    return val1 * val2
}// 여기서 multiply의 자료형은 (Int, Int) -> Int

 

let result = multiply(10, 20) //상수를 함수처럼 호출,200

 

후행 클로저(trailing closure)

클로저가 함수의 마지막 argument라면 마지막 매개변수명(cl)을 생략한 후 함수 소괄호 외부에 클로저를 작성


https://docs.swift.org/swift-book/documentation/the-swift-programming-language/closures/

 

func someFun(cl: () -> Void) { 



// trailing closure를 사용 안하면

 

someFun(cl: {
    //closure’s body 
})
// trailing closure 사용


someFun() { 

    //trailing closure
's body goes here 

}

클로저가 함수의 마지막 argument라면 마지막 매개변수 이름(handler:)을 생략한 후 함수 소괄호 외부에 클로저를 구현

let onAction = UIAlertAction(title: "On", style: UIAlertAction.Style.default) { 
    ACTION in self.lampImg.image = self.imgOn
    self.isLampOn=true
}


let removeAction = UIAlertAction(title: "제거", style: UIAlertAction.Style.destructive, handler: { 
    ACTION in self.lampImg.image = self.imgRemove
    self.isLampOn=false
})

클로저의 축약 표현들


클래스(class)


클래스의 기본 구조


class 새로운 클래스 이름 : 부모 클래스 {
// 프로퍼티
// 인스턴스 메서드
// 타입(type) 메서드(클래스 메서드)

 

프로퍼티는
1. 초기값이 있거나
2. init을 이용해서 초기화하거나
3. 옵셔널 변수(상수)로 선언(자동으로 nil로 초기화) 해야한다.

Initializer

failable initializer(실패 가능한 생성자: init?)*


nil값도 저장할 수 있으려면 init다음에 "?"를 하며 옵셔널 값이 리턴됨

 

init?(named: String) // failable initializer

 

init?로 만든 인스턴스는 옵셔널형으로 만들어져서, 사용하려면 옵셔널을 언래핑해야 해서 위의 예제에서 제일 마지막에 "!"가 있음

init다음에 "?"나 "!"를 하며 옵셔널 값이 리턴됨

 

오류 상황에 nil을 리턴하는 조건문이 있음

init? / init!

1, 2번째 방법이 좋고 3, 4번째 방법은 위험해서 비추 한다.

보통 2번째 방법을 많이 씀