본문 바로가기
2022_iOS 앱 개발자 워크숍/1, Swift 문법 복습

Swift : Implicity Unwrapped ( 암묵적 언래핑 )

by 황민우 2022. 1. 3.

 

- 클래스의 아웃렛 변수 초기화에서 많이 사용 (자동 생성 코드)
- 옵셔널이 항상 유효한 값을 가질 경우 암묵적인 언래핑(Implicity unwrapped)이 되도록 선언할 수 있음
- 암묵적인 언래핑으로 옵셔널을 선언하기 위해선 선언부에 ! 사용

 

 

예제 1

let x : Int? = 1
let y : Int = x!
let z = x
print(x,y,z)
print(type(of:x),type(of:y),type(of:z))

// Optional(1) 1 Optional(1)
// Optional<Int> Int Optional<Int>

 

예제 2

let a : Int! = 1
let b : Int = a
let c : Int = a!
let d = a
let e = a + 1
print(a,b,c,d,e)
print(type(of:a),type(of:b),type(of:c),type(of:d),type(of:e))

// Optional(1) 1 1 Optioanl(1) 2
// Optional<Int> Int Int Optional<Int> Int

 

예제 3

class MyAge {
    var age : Int!
    init(age: Int) {
        self.age = age
    }
    func printAge() {
        print(age)						// Optional(1)
        print(age+1)					// 2
        let age1 : Int = age
        print(age1)						// 1
        let age2 = age + 2
        print(age2)						// 3
    }
}
var SeaGreen = MyAge(age:1)
SeaGreen.printAge()

강의 출처 : https://www.youtube.com/channel/UCM8wseo6DkA-D7yGlCrcrwA

댓글