as구문

Wongbing·2022년 1월 8일
0

as구문에 대하여...

import Foundation

class Animal {
    var name: String
    
    init(n: String) {
        name = n
    }
}

class Human: Animal {
    func code() {
        print("Typing away...")
    }
}

class Fish: Animal {
    func breathUnderWater() {
        print("Breathin under water.")
    }
}

let angela = Human(n: "Angela Yu")
let jack = Human(n: "Jack Bauer")
let nemo = Fish(n: "Nemo")

let neighbours = [angela, jack, nemo]

func findNemo(from animals: [Animal]){
    for animal in animals {
        if animal is Fish{
            print(animal.name)     
            let fish = animal as! Fish//Fish --> subclass Animal --> superclass forced downcast
            fish.breathUnderWater()  
            let animalFish = fish as Animal // as --> raise a object to its superclass type Upcast
        }
    }
}

findNemo(from: neighbours)

if let fish = neighbours[1] as? Fish { //Humanclass인 jack을 Fish로 옵셔널바인딩
    fish.breathUnderWater()
} 

profile
IOS 앱개발 공부

0개의 댓글