Type Casting(타입 캐스팅)

장수빈·2024년 6월 11일

Swift문법

목록 보기
10/11

Determine a value’s runtime type and give it more specific type information.

값의 런타임 타입을 정하고 타입의 정보를 제공합니다.

  • 타입 캐스팅은 인스턴스의 타입을 확인합니다.
  • 인스턴스를 다른 상위 클래스 또는 하위 클래스로써 취급하는 방법입니다.

예제

클래스 계층 정의

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)
    }
}

let library = [
    Movie(name: "Casablanca", director: "Michael Curtiz"),
    Song(name: "Blue Suede Shoes", artist: "Elvis Presley"),
    Movie(name: "Citizen Kane", director: "Orson Welles"),
    Song(name: "The One And Only", artist: "Chesney Hawkes"),
    Song(name: "Never Gonna Give You Up", artist: "Rick Astley")
]
// the type of "library" is inferred to be [MediaItem]

타입 검사(Checking Type)

type check operator is 를 사용하여 타입을 검사합니다.
인스턴스가 하위 클래스 타입이면 true 아니면 false 를 반환합니다.

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")
// Prints "Media library contains 2 movies and 3 songs"

다운캐스팅 (Downcasting)

type cast operator as? 또는 as!를 사용하여 하위 클래스 타입으로 다운 캐스트 (downcast) 할 수 있습니다.

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)")
    }
}

// Movie: Casablanca, dir. Michael Curtiz
// Song: Blue Suede Shoes, by Elvis Presley
// Movie: Citizen Kane, dir. Orson Welles
// Song: The One And Only, by Chesney Hawkes
// Song: Never Gonna Give You Up, by Rick Astley

as? 는 옵셔널 값을 반환하고 다운캐스팅에 실패하게 되면 nil을 반환합니다.
as! 는 옵셔널에서와 같게 강제 언래핑을 합니다. 다운캐스팅에 실패하게 되면 런타임 에러를 발생시킵니다.

출처 : https://bbiguduk.gitbook.io/swift/language-guide-1/type-casting

profile
iOS 공부 이모저모 낙서장

0개의 댓글