[Swift Deep Dive] Casting as? as! as is and understanding

Woozoo·2022년 12월 21일
0
import Foundation

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

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

class Fish: Animal {
	func breathe UnderWater() {
    	print("Breathing under water.")
    }
}

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

let neighbours = [angela, jack, nemo]

let neighbour1 = neighbours[0]

if neighbours[0] is Human {
	print("First Neighbour is a Human")
}

func findNemo(from animals: [Animal]) {
	for animal in animals {
    	if animal is Fish {
        	print(animal.name)
            //animal.breatheUnderWater() 안됨..
            let fish = animal as! Fish
            fish.breatheUnderWater()
            let animalFish = fish as Animal
        }
    }
}

findNemo(from: neighbours)

if let fish = neighbours[1] as? Fish {
	fish?.breatheUnderWater()
} else {
	print("Casting has failed")
}

// 이거는 타입캐스팅이 아님 이니셜라이저임
let myDouble = 0.0
let myDoubleAsAnInt = Int(myDouble)

느낌표는 Forced Down Cast
as는 슈퍼클래스 타입으로 바꿔주는 거 ( 단계업! ) : Upcast

let neighbours: [Any] = ["hello", 1, 1.1]

Any면 다 가능
AnyObject면? class인 것만 가능
NSObject면? NS 붙은 것만 가능

profile
우주형

0개의 댓글