[Swift] 利用 is 和 as 的來做型別檢查與轉換

在 Swift 中,如果要做型別的轉換,通常我們會使用 as 來做型別的轉換,於是許多人也順便用 as 來做型別的檢查,而其實 swift 本身就有 is 關鍵字來判斷型別囉,怎麼用呢?

swift 1

答案是很簡單的,我們先看一下以下最基本的程式。

class Animal {
    func run() {
        print("Animal runs")
    }
}

class Dog: Animal {
    override func run() {
        print("Dog runs")
    }
}

class Cat: Animal {

    func makeSound() {
        print("Cat makeSound")
    }

    override func run() {
        print("Cat runs")
    }
}

let animal = Animal()
let dog = Dog()
let cat = Cat()
let animals: [Animal] = [Cat(), Dog()]

假設我們要將判斷我們陣列的動物群是不是狗或貓,我們可以用以下的程式碼。這時我會使用 is 來做型別檢查 (type checking),因為我們只是要判斷他是貓或狗而已,並沒有要做任何事。

for animal in animals {
    if animal is Dog { // 如果動物是狗
        print("It's a dog!")
    } else if animal is Cat {
        print("It's a cat!")
    }
}

如是轉型後的變數需要做某些事我才會用 as,以下列的例子來說,當我轉成 dog 和 cat 時,我還需要呼叫 dog 和 cat 這個類別中的函式來做某些事,所以我才會用 as 來做型別轉換 (type casting)。

for animal in animals {
    if let dog = animal as? Dog { // 如果動物是狗
        dog.run()
    } else if let cat = animal as? Cat {
        cat.makeSound()
        cat.run()
    }
}

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments