Swift/swift 문법

as 연산자 / is 연산자

Lyla. 2023. 5. 26. 19:36

상속은 필요한 데이터를 추가하는 메모리 구조 

 

 

undergraduate 타입은 person을 상속받는다. 

메모리 구조 -> person에서 undergraduate의 프로퍼티가 추가된다. 

 

is 연산자 

: 특정 타입이 맞는지 확인한다. 

반환값: Bool type

 

as 연산자

: 인스턴스 타입의 힌트를 변경하는 연산자. 

다운캐스팅에 성공할 경우, 접근가능한 항목(상속받은 클래스의 프로퍼티)의 수를 늘려준다. 

 

 

let person: Person = Undergraduate() 

-> Person: 변수에 정의된 타입 

Undergraduate: 실제 메모리 공간의 인스턴스 

 

Person type보다 Undergraduate type 항목의 개수가 더 많다. 

하지만 현재 Person type으로 person변수에는 정의되어 있으므로 Person type의 프로퍼티만 접근 가능하다. (오개념)

-> person의 타입은 Undergraduate이나, Person의 프로퍼티에만 접근할 수 있다. 

let apple:Fruit = Rosaceae()
print(type(of: apple))     ////Rosaceae

type을 print해보면 Rosaceae type으로 출력된다.

하지만  Rosaceae class에서 추가된 프로퍼티에는 접근 불가. 

 

-> 타입 캐스팅 필요. 

접근 가능한 프로퍼티를 늘려주기 위해서는 as? 연산자로 타입을 바꾸어 주어야 한다.

 

 

ex. if let apple = person as? Rosaceae

person을 Rosaceae로 바인딩해서 사용 

 

성공하면 옵셔널 값이 추출

 

 

[코드 예시]

class Fruit {
    var flower:String
    var tree:Bool
    
    init() {
        self.flower = "rose"
        self.tree = false
    }
}

//fruit을 상속받는 Rosaceae
class Rosaceae: Fruit {
    var color : String
    
    override init() {
        //자신의 메모리 구조를 초기화 한 후 상위(부모) 속성의 메모리 이니셜라이저 호출이 필요.
        self.color = "blue"
        super.init()
    }
}

//타입 힌트는 Fruit이지만 실제 메모리 구조는 Rosaceae로 생성
let apple:Fruit = Rosaceae()
print(type(of: apple))     ////Rosaceae
apple.tree
apple.flower

//Fruit type의 프로퍼티에만 접근할 수 있다. (에러)
//apple.color


//apple 인스턴스를 Rosaceae로 타입캐스팅하여 appleWithRose에 담는다.
if let appleWithRose = apple as? Rosaceae {
    print(type(of: apple))          //Rosaceae
    print(type(of: appleWithRose))  //Rosaceae
    
    //Rosaceae type의 프로퍼티 flower에 접근 가능하도록 변경됨.
    print(appleWithRose.flower)
}