🔥 타입 확인하기
is 연산자를 사용하면 인스턴스가 특정 서브클래스 타입인지 확인할 수 있어요. 인스턴스가 해당 서브클래스 타입이면 true를, 그렇지 않으면 false를 반환하지요.
아래 예제는 library 배열에서 Movie와 Song 인스턴스의 수를 세는 movieCount와 songCount 두 개의 변수를 정의하고 있어요.
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") // "Media library contains 2 movies and 3 songs" 출력swift
이 예제는 library 배열의 모든 항목을 순회하고 있어요. 각 패스에서 for-in 루프는 item 상수를 배열의 다음 MediaItem으로 설정합니다.
item is Movie는 현재 MediaItem이 Movie 인스턴스이면 true를, 그렇지 않으면 false를 반환해요. 마찬가지로 item is Song은 항목이 Song 인스턴스인지 확인하지요. for-in 루프가 끝나면, movieCount와 songCount의 값은 각 타입의 MediaItem 인스턴스가 몇 개 발견되었는지를 나타내게 됩니다.
이처럼 is 연산자를 사용하면 런타임에 인스턴스의 실제 타입을 확인할 수 있어요. 이는 다형성을 활용하여 코드를 유연하게 작성할 때 매우 유용하답니다.
예를 들어, 아래와 같이 MediaItem 배열에 다양한 서브클래스 인스턴스를 저장할 수 있어요.
let mediaItems: [MediaItem] = [ Movie(name: "The Godfather", director: "Francis Ford Coppola"), Song(name: "Bohemian Rhapsody", artist: "Queen"), Movie(name: "The Dark Knight", director: "Christopher Nolan"), Song(name: "Stairway to Heaven", artist: "Led Zeppelin") ]swift
그리고 is 연산자를 사용하여 각 항목의 실제 타입을 확인하고, 그에 따라 적절한 동작을 수행할 수 있지요.
for item in mediaItems { if item is Movie { print("Movie: \(item.name)") } else if item is Song { print("Song: \(item.name)") } }swift
이렇게 하면 아래와 같은 출력 결과를 얻을 수 있답니다.
Movie: The Godfather Song: Bohemian Rhapsody Movie: The Dark Knight Song: Stairway to Heaventext
타입 확인은 타입 캐스팅의 첫 번째 단계라고 할 수 있어요. is 연산자로 원하는 타입인지 확인한 후, 맞다면 as 연산자를 사용하여 해당 타입으로 캐스팅할 수 있지요. 이에 대해서는 다음 섹션에서 자세히 알아볼 거예요!