티스토리 뷰

🍏/Swift

[Swift] 다운캐스팅(downcasting)

eungding 2018. 2. 20. 18:10
반응형


다운캐스팅(downcasting) = 부모클래스의 타입을 자식클래스의 타입으로 다운하여 캐스팅한다 


다운캐스팅이 쓰이는 경우 2가지 예제를 정리하려고 한다. 하나는 기본 swift 예제 , 하나는 지금 앱개발하면서 커스텀 뷰안에서 쓰고 있는 예제


ex -1 ) 


다음과 같은 클래스가 있다고 하자

부모클래스인 디저트클래스와 이를 상속받은 자식클래스 두개 아이스크림클래스와 초콜릿클래스!


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
32
33
34
35
36
37
38
39
40
class Dessert{
    let name:String
    let cal:Int
    
    var description:String{
        return "\(name)은 \(cal)칼로리..하지만 맛있게 먹으면 0칼로리"
    }
    
    init(name:String,cal:Int) {
        self.name = name
        self.cal = cal
    }
}
 
class Icecream:Dessert{
    let flavor:String
    
    override var description:String{
        return "\(flavor)맛 \(name)은 \(cal)칼로리..하지만 맛있게 먹으면 0칼로리"
    }
    
    init(name: String, cal: Int, flavor:String) {
        self.flavor = flavor
        super.init(name: name, cal: cal)
    }
}
 
class Chocolate:Dessert{
    let cacaoPercent:Int //카카오함유량
    
    override var description:String{
        return "카카오함유량\(cacaoPercent)% \(name)은 \(cal)칼로리..하지만 맛있게 먹으면 0칼로리"
    }
    
    init(name: String, cal: Int, cacaoPercent:Int) {
        self.cacaoPercent = cacaoPercent
        super.init(name: name, cal: cal)
    }
    
}
cs

 

타입캐스팅의 3가지 방법

   1) as! = 강제 타입 변환 -> 안쓰는 좋다

   2) as? = 옵셔널 타입 변환 

   3) as = 넘나 당연한 타입변환 ex) 디저트클래스타입을 디저트클래스타입으로 형변환



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
32
33
//보통 이런식으로 쓰이지만
let dessert = Dessert(name: "달달구리디저트", cal: 1000)
let icecream = Icecream(name: "바세츠아이스크림", cal: 500, flavor: "체리치즈")
let chocolate = Chocolate(name: "이마트다크초콜릿", cal: 480, cacaoPercent: 58)
 
//아이스크림 인스턴스를 참조하고 있지만 디저트 타입 인척하는 참조변수도 있다
let icecream2:Dessert = Icecream(name: "바세츠아이스크림", cal: 500, flavor: "딸기치즈")
type(of: icecream2) //output = 디저트
 
 
// 왜때문에? 편의를 위해 이런식의 배열로 묶여서 자주 쓰이기 때문이다
// 다형성(=dynamic binding) : 하나의 객체를 형태 또는 타입를 바꿔서 사용할 수 있다 이라고 표현한다
var dessertList:[Dessert] = []
dessertList.append(icecream)
dessertList.append(icecream2)
dessertList.append(dessert)
dessertList.append(chocolate)
 
if let icecream = dessertList.first as? Icecream{
    print(icecream.description)
else{
    print("다운캐스팅 실패")
}
 
//output = 체리치즈맛~
 
if let chocolate = dessertList.last as? Chocolate{
    print(chocolate.description)
else{
    print("다운캐스팅 실패")
}
 
//output = 카카오함유랑~
cs



https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TypeCasting.html

여기 예제 너무 좋다 

반응형
댓글