iOS/๐ŸŸ  Swift

Type Casting Overview - Type Casting

woozzang 2021. 1. 21. 00:42

Type Casting ์€ ๋‘ ๊ฐ€์ง€๋ฅผ ๊ฐ€๋ฆฌํ‚ต๋‹ˆ๋‹ค.

 

1. ์ธ์Šคํ„ด์Šค์˜ ํƒ€์ž…์„ ํ™•์ธํ•˜๋Š” ์ˆ˜๋‹จ์ž…๋‹ˆ๋‹ค.

  ์—ฌ๊ธฐ์—๋Š” ` is ` ํ‚ค์›Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.

 

2. ์ธ์Šคํ„ด์Šค๋ฅผ ๊ทธ ํด๋ž˜์Šค์˜ ์ƒ์†๊ณ„์ธต์˜ Superclass ํ˜น์€ Subclass๋กœ ์ทจ๊ธ‰ํ•˜๊ฒŒ ํ•ฉ๋‹ˆ๋‹ค.

  ์—ฌ๊ธฐ์—๋Š” ` as ` ํ‚ค์›Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.

 

์—ฌ๊ธฐ์„œ ๋‹ค๋ฅธ ํƒ€์ž…์œผ๋กœ ์ทจ๊ธ‰ํ•œ๋‹ค (treat) ๋Š” ์˜๋ฏธ๋Š”, ๊ธฐ์กด ์ธ์Šคํ„ด์Šค์˜ ํƒ€์ž…์„ ๋ณ€๊ฒฝํ•˜๋Š” ๊ฒƒ๊ณผ๋Š” ์ฐจ์ด๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค.

์ „์ž๋Š” Type Casting ์„ ๊ฐ€๋ฆฌํ‚ค๊ณ , ํ›„์ž๋Š” Type Conversion์„ ๊ฐ€๋ฆฌํ‚ต๋‹ˆ๋‹ค.

 

์ถ”๊ฐ€์ ์œผ๋กœ ํ”„๋กœํ† ์ฝœ๋„ ํ•˜๋‚˜์˜ ๋…๋ฆฝ์ ์ธ ํƒ€์ž…์ด๊ณ , ์ƒ์†์ด ๊ฐ€๋Šฅํ•˜์—ฌ ์ƒ์†๊ณ„์ธต์ด ํ˜•์„ฑ๋˜๋ฏ€๋กœ Type Casting์„ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

๊ฒฐ๊ตญ Type Casting ์€ Class ์™€ Protocol์— ํ•œ์ •ํ•˜์—ฌ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 


 

Defining a Class Hierarchy for Type Casting

 

๋‹ค์Œ ์ฝ”๋“œ๋Š” ์ฃผ์–ด์ง„ ์ƒํ™ฉ์ž…๋‹ˆ๋‹ค.

class Transportation {
    var fare: Int
    init(fare: Int) {
        self.fare = fare
    }
}

/* Transportaion ์˜ Subclass */
class Metro: Transportation {
    var lineNumber: Int
    init(fare: Int, lineNumber: Int) {
        self.lineNumber = lineNumber
        super.init(fare: fare)
    }
}

/* Transportaion ์˜ ๋˜ ๋‹ค๋ฅธ Subclass */
class Bus: Transportation {
    var busNumber: Int
    init(fare: Int, busNumber: Int) {
        self.busNumber = busNumber
        super.init(fare: fare)
    }
}

์•„~์ฃผ ๊ฐ„๋‹จํ•œ ์ƒ์† ๊ณ„์ธต ๊ตฌ์กฐ๋„

 

์•„๋ž˜ ์ฝ”๋“œ๋Š” ํƒ€์ž… ์„ ์–ธ ์—†์ด ๋ฐฐ์—ด์— Trasnportation ์˜ Subclass ๋‘ ๊ฐœ์˜ ์ธ์Šคํ„ด์Šค๋ฅผ ๋ฌด์ž‘์œ„๋กœ ์ง‘์–ด๋„ฃ๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค.

 

์ด ๊ฒฝ์šฐ, list ๋Š” [Transportation] ํƒ€์ž…์œผ๋กœ ํƒ€์ž… ์ถ”๋ก  (Type Inference) ๋ฉ๋‹ˆ๋‹ค.

Swift's type checker is able to deduce that two subclasses have a common superclass of Transportation.

 

let list = [
    Metro(fare: 1000, lineNumber: 3),
    Bus(fare: 700, busNumber: 6617),
    Metro(fare: 1100, lineNumber: 9),
    Bus(fare: 900, busNumber: 700),
    Bus(fare: 2700, busNumber: 100)
]

// ํƒ€์ž… ์ถ”๋ก  ๋˜์–ด list๋Š” [Transportation] ํƒ€์ž…์ด ๋จ

 

๋ฉค๋ฒ„๋“ค๋„ ๋ชจ๋‘ Transportaion ํƒ€์ž…์œผ๋กœ ์บ์ŠคํŒ…๋œ ๊ฒƒ์ž…๋‹ˆ๋‹ค!

์—„๋ฐ€ํžˆ ๋งํ•˜๋ฉด ์—…์บ์ŠคํŒ… ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.

 

 

 

๋!


๋‹ค์Œ ๊ธ€: Checking Type & Downcasting - Type Casting

 

Checking Type & Downcasting - Type Casting

Checking Type /* item ์ด Transportation ํƒ€์ž…์œผ๋กœ Upcasting ๋˜์–ด ์žˆ๋Š” ์ƒํ™ฉ */ ... if item is Metro { } else if item is Bus { } ... Type check operator ` is ` ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ธ์Šคํ„ด์Šค๊ฐ€ ํŠน์ • subclass ํƒ€..

woozzang.tistory.com