型をダウンキャストする方法
Swift における型変換について調べました。
as?
演算子の基本です。
こんな継承したAnimal型があって
Animal型とその継承クラス
class Animal {
// 体重とか
}
class Dog: Animal {
var name: String
}
class Cat: Animal {
var boxSize: Int
}
class Bird: Animal {
let featherColor: Color
}
こんな関数があって
Animal型を返す関数
func getPet() -> Animal {
// return the pet
}
let pet = getPet() //petはAnimal型
この時点で、pet
の具体的な型は不明。
Dog
かも知れないし、Cat
かも知れないし、Bird
かも知れない。
ペットの種類に合わせたタスク
func walk(dog: Dog) {
// お散歩させる
print("Walking with \(dog.name)")
}
func cleanLitterBox(cat: Cat) {
// ネコ用トイレを掃除する
print("Cleaning the \(cat.boxSize) litter box")
}
func cleanCage(bird: Bird) {
// 鳥かごをキレイにする
print("Removing the \(bird.featherColor) feathers")
}
ペットに合わせたタスクを行う関数があるけど、定数 pet
を引数にするとエラーになる可能性がある。
ダウンキャストして、適切にタスクを実行する
as?
と if-let
ステートメントを組み合わせて、型キャストしつつオプショナルをアンラップする。
ダウンキャストの例
let pets = allPetAnimals() //あらゆる種のペットを含んだ配列
for pet in pets {
if let dog = pet as? Dog {
walk(dog: Dog)
} else if let cat = pet as? Cat {
cleanLitterBox(cat: Cat)
} else if let bird = pet as? Bird {
cleanCage(bird: Bird)
} else {
print("The type of this pet is unknown.")
}
}