Language/Swift 수업

iOS 프로그래밍 기초 (5)

비코딩 2021. 10. 2. 04:14

[iOS프로그래밍기초(21-2학기)한성현교수님 강의 내용 변형 및 요약]

1급 객체

다음 세 조건을 만족하는 객체를 1급 객체라고 한다.

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

1. 함수를 변수에 저장

Swift는 함수를 데이터 타입처럼 처리할 수 있는 1급 객체이다. 함수를 상수나 변수에 저장하는 것이 가능하다.

func inchesToFeet (inches: Float) -> Float {
    return inches * 0.0833333
}
let toFeet = inchesToFeet   // 함수를 자료형처럼 사용

print(inchesToFeet(inches:10))
print(toFeet(10))   // 매개변수형 사용X, (inches:10) 사용하면 에러

2. 함수를 매개변수로 사용

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

func outputConversion(converterFunc: (Float) -> Float, value: Float) {//함수를 매개변수로 사용
    let result = converterFunc(value) //toFeet(10)
    print("Result = \(result)")
}
outputConversion(converterFunc:toFeet, value: 10) // 피트로 변환하는 inchesToFeet함수 호출

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(converterFunc:toYards, value: 10) // 야드로 변환하는 inchesToYards함수 호출
outputConversion(converterFunc:toFeet, value: 10) // 피트로 변환하는 inchesToFeet함수 호출

func decideFunction (feet: Bool) -> (Float) -> Float { //매개변수형 리턴형이 함수형
    if feet {
        return toFeet //함수를 리턴
    } else {
        return toYards
    }
}

1급 객체 실습

func diploic(num: Double) -> Double {
    return num *2
}
func half(num: Double) -> Double {
    return num /2
}
let toDiploic = diploic
print(diploic(num:7))
print(toDiploic(7))
let toHalf = half
func twice(Which: (Double) -> Double, num: Double) {
    let result = Which(num)
    print("결과 = \(result)")
}
twice(Which:toDiploic, num: 7) //toDiploic(7)
twice(Which:toHalf, num: 7) //toHalf(7)
func decideTwice(a: Bool) -> (Double) -> Double { //매개변수형 리턴형이 함수형
    if a {
        return toDiploic
    } 
    else {
        return toHalf
    }
}
let b = decideTwice(a:false) // let b = toHalf
print(type(of:b)) //(Double) -> Double
print(b(6)) // toHalf(6)
// 14.0, 14.0, 결과 = 14.0, 결과 = 3.5, (Double) -> Double, 3.0

 

클로저(closure)

  • 익명 함수
  • 클로저 표현식은 독립적인 코드 블록
  • 함수가 한 번만 호출이 될 때 함수를 선언하지 않고 바로 사용하기 위해서 클로저 사용
// 기존
func multiply(a: Int, b: Int) -> Int { 
    return(a*b)
}

// 클로저
let multiply2 = {(a: Int, b: Int) -> Int in
    return(a*b)
}

print(multiply2(5,7))   //35
{ ( <매개변수 이름>:  <매개변수 타입>, ...) -> <반환 타입> in
     // 클로저 표현식 코드
}

 

후행 클로저(trailing closure)

func avg(a: Double, b: Double, method: (Double, Double) -> Double) -> Double {
    return method(a, b)
}

var result: Double = avg(a: 10, b: 15, method: {(left: Double, right: Double) -> Double in
    return (left + right) / 2
})
print(result)   // 12.5

// 후행 클로저
result = avg(a: 10, b: 15) {(left: Double, right: Double) -> Double in  
    return (left + right) / 2
}
print(result)   // 12.5

// 리턴형 생략
result = avg(a: 10, b: 15) {(left: Double, right: Double) in  
    return (left + right) / 2
}
print(result)   // 12.5

// 매개변수(, in) 생략
result = avg(a: 10, b: 15) { 
    return ($0 + $1) / 2    // 단축인자 : 매개변수의 순서대로 $0, $1 ...
}
print(result)   // 12.5

// return 생략
result = avg(a: 10, b: 15) {($0 + $1) / 2}   // 클로저 마지막 줄은 반환값(return)
print(result)   // 12.5

 

클래스

class 클래스이름 : 부모클래스 {
     // 프로퍼티(property)
     // 인스턴스 메소드
     // 타입(type) 메소드 (=클래스 메소드)
}
  • '프로퍼티'는 클래스 내에 포함되는 변수(var)와 상수(let)을 정의
  • '인스턴스 메소드'는 객체가 호출하는 메소드를 정의
  • '타입 메소드'는 클래스가 호출하는 메소드를 정의 ex) static ~

 

프로퍼티

  • 프로퍼티는 클래스, 구조체 열거형과 관련한 값이다.
  • 종류로는 저장 프로퍼티(Stored Properties)와 계산된 프로퍼티(Computed Properties)가 있다.
  • 저장 프로퍼티 : 값을 저장하고 있는 프로퍼티, 클래스와 구조체에서만 사용 가능
  • 계산된 프로퍼티 : 계산한 값을 반환해 주는 프로퍼티, 클래스, 구조체, 열거형 모두에서 사용가능

 

클래스에 저장 프로퍼티 추가하기

    1. 초기값을 지정
    2. init을 이용해서 초기화
    3. 옵셔널 변수(상수)로 선언
class Man{ 
	var age : Int = 1 
    var weight : Double = 3.5 
    func display (){ 
    	//인스턴스 메서드 print("나이 =\(age), 몸무게 =\(weight)") 
    }
}​​

위 세가지 방법 중 하나의 방법으로도 하지 않으면 에러

 

메소드

인스턴스 메소드, 클래스 또는 타입 메소드

class Student{
    var age : Int = 23
    var weight : Double = 55
    func display() {
        print("나이=\(age), 몸무게=\(weight)")
    }
}
var shim : Student = Student()  // : Student 생략 가능
shim.display() // 나이=23, 몸무게=55.0 인스턴스 메서드는 인스턴스가 호출
print(shim.age) // 23