<aside> ๐Ÿ’ก Type Casting

</aside>

https://docs.swift.org/swift-book/LanguageGuide/TypeCasting.html

์‹œ์ž‘ํ•˜๊ธฐ ์ „์—

class Animal {}
class Human: Animal {}
class Dog: Animal { func roar(){...} }
...
var whatTypeIs = [ human, dog ]

Animal์„ ์ƒ์†๋ฐ›๋Š” Human๊ณผ, Dog class ๊ฐ€ ์žˆ๊ณ , ๋‘๊ฐœ์˜ ์ธ์Šคํ„ด์Šค๋ฅผ ๊ฐ€์ง„ ๋ฐฐ์—ด์„ ๋งŒ๋“ค๋ฉด

swift๋Š” ์ตœ์ƒ์œ„ ํด๋ž˜์Šค์ธ 'Animal' ํƒ€์ž…์„ ๊ฐ–๋Š” ๋ฐฐ์—ด์„ ๋งŒ๋“ค์–ด ์ค€๋‹ค.

is

Object์˜ Data Type์„ ํ™•์ธ(check)ํ•ด์ฃผ๋Š” ํ‚ค์›Œ๋“œ

//use for Type Checking
let cell = UITableViewCell()
if cell is UITableViewCell() {
	//if true
}

[sample code]

// When use the 'is' keyword?
func findDog(from animals: [Animal]) {
    for animal in animals {
        if animal is Dog {
            print("Find the dog!, \\(animal.name)")
        }
    }
}

findDog(from: neighbors)

์œ„์˜ ์ฝ”๋“œ์™€ ๊ฐ™์ด ๋ฐฐ์—ด์— ์–ด๋–ค ํด๋ž˜์Šค๊ฐ€ ๋“ค์–ด์žˆ๋Š”์ง€ ํ™•์ธํ•˜๊ณ  ์‹ถ์„ ๋•Œ, is ํ‚ค์›Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

as! Exclamation mark

forced downcast

<aside> ๐Ÿ’ก ์–ธ์ œ ๋‹ค์šด์บ์ŠคํŠธ๊ฐ€ ํ•„์š”ํ• ๊นŒ?

</aside>

func findDog(from animals: [Animal]) {
    for animal in animals {
        if animal is Dog {
            print("Find the dog!, \\(animal.name)")
            // ์šฐ๋ฆฌ๋Š” animal์ด Dog์ธ๊ฑธ ํ™•์‹ ํ•˜์ง€๋งŒ ์ปดํŒŒ์ผ๋Ÿฌ๋Š” ๊ทธ๋ ‡์ง€ ์•Š๋‹ค.
            ๐Ÿคฌ์—๋Ÿฌ -> animal.roar() //because animal์˜ ๋ฐ์ดํ„ฐ ํƒ€์ž…์€ 'Animal'์ด๊ธฐ ๋•Œ๋ฌธ์—
            // Need!!Forced Down cast, Animal -> Dog or Human (super -> sub class)
            let dog = animal as! Dog
            dog.roar()
        }
    }
}