조앤의 기술블로그

[Swift] Type Casting (타입 캐스팅) 본문

Study/Swift

[Swift] Type Casting (타입 캐스팅)

쬬앤 2020. 2. 25. 14:45

타입캐스팅은 인스턴스의 형식을 확인하거나, 인스턴스를 다른 형식으로 처리할 때 사용합니다. 

(Type casting is a way to check the type of an instance, or to treat that instance as a differenct superclass or subclass from somewhere else in its own class hierarchy.)

 

스위프트에서 타입캐스팅은 is와 as 연산자로 구현됩니다. (프로토콜을 활용해서 타입캐스팅을 하는 방법도 있지만, 이 포스팅에서는 다루지 않겠습니다. )

class MediaItem {
	var name: String
    init(name: String) {
    	self.name = name
    }
}
class Movie: MediaItem {
	var director: String
    init(name: String, director: String) {
    	self.director = director
        super.init(name: name:)
    }
}

class Song: MediaItem {
	var artist: String
    init(name: String, artist: String) {
    	self.artist = artist
        super.init(name: name)
    }
}​

Movie, Song 클래스는 MediaItem 클래스를 상속하고 있습니다. 

let library = [
	Movie(name: "기생충", director: "봉준호"),
    Song(name: "ON", artist: "BTS"),
    Movie(name: "아이리시맨", director: "마틴 스코세이지"),
    Movie(name: "결혼이야기", director: "노아 바움백"),
    Song(name: "Interlude: Shadow", artist: "SUGA")
]

// library 의 자료형은 [MediaItem]

library 배열의 자료형은 MediaItem입니다. 

 

<Checking Type>

var movieCount = 0
var songCount = 0

for item in library {
	if item is Movie {
    	movieCount += 1
    } else if item is Song {
    	songCount += 1
    }
}

print("Media library contains \(movieCount) movies and \(songCount) songs")
// 3 2

is 연산자를 통해 형식을 확인할 수 있습니다. 

library 배열의 item이 Movie 형식이라면 if 문이 실행되고, Song이라면 else if 문이 실행됩니다. 

 

<Downcasting>

for item in library {
	if let movie = item as? Movie {
    	print("Movie: \(movie.name), dir. \(movie.director)")
    } else if let song = item as? Song {
    	print("Song : \(song.name), by \(song.artist)")
    }
}

다운캐스팅은 MediaItem의 자료형인 item이 Movie, Song의 각 속성에 접근해야 할 때 필요합니다. 

MediaItem의 자료형으로는 Movie와 Song의 속성인 director나 artist에 접근할 수 없습니다. 

 

여기서 as? 연산자는 다운캐스팅이 성공할 경우 옵셔널 자료형을 리턴하고, 실패할 경우 nil을 리턴합니다. 

 

as! 연산자도 있는데, 이 연산자는 다운캐스팅이 성공하면 unwrapping한 자료형은 리턴하고, 실패할 경우 런타임 에러가 발생합니다. 따라서 다운캐스팅 성공이 확신될 경우에만 사용하는 것이 좋습니다. 

 

코드 출처 : https://docs.swift.org/swift-book/LanguageGuide/TypeCasting.html

 

Type Casting — The Swift Programming Language (Swift 5.2)

Type Casting Type casting is a way to check the type of an instance, or to treat that instance as a different superclass or subclass from somewhere else in its own class hierarchy. Type casting in Swift is implemented with the is and as operators. These tw

docs.swift.org

 

'Study > Swift' 카테고리의 다른 글

[Swift] Initializers #2  (0) 2020.02.26
[Swift] Initializers #1  (0) 2020.02.26
[Swift] Inheritance and Polymorphism(상속과 다형성)  (0) 2020.02.24
[Swift] Method and Subscript  (0) 2020.02.21
[Swift] Property(프로퍼티) #2  (0) 2020.02.20