-
[Swift] ํ์ ์บ์คํ (type casting)iOS/Swift 2022. 8. 24. 23:53
๐ก ์ค์ํํธ์ ํ์ ์บ์คํ ์ C++๊ณผ ๋ค๋ฅด๋ค๋ ๊ฑธ ์ดํดํ๊ณ ๋์ด๊ฐ์!!!
์ด๊ฑธ ๋ชจ๋ฅด๊ณ ๊ณต๋ถํ๋ฉด ํท๊ฐ๋ฆฐ๋ค
C++์ ํ๋ณํ(ํ์ ์บ์คํ )
- ๋ฌต์์ ํ๋ณํ
์ปดํ์ผ ํ ๋ ์๋์ผ๋ก ํ๋ณํ ๋๋ค.
float a = 3.14; int b; b = a; // 3
- ๋ช ์์ ํ๋ณํ
๊ฐ๋ฐ์๊ฐ ์ง์ ํ์ ์ ๋ช ์ํด์ค๋ค.
float a = 3.14; int b; b = (int)a; // 3
Swift์ ํ๋ณํ(์ด๋์ ๋ผ์ด์ )
var a: Double = 3.14 var b: Int = Int(a) print(b) // 3
Swift๋ ๊ธฐ์กด ๊ฐ(a)์ ์ ๋ฌ์ธ์๋ก ๋ฐ๋ ์ด๋์ ๋ผ์ด์ ๋ฅผ ํตํด ์๋ก์ด ์ธ์คํด์ค๋ฅผ ์์ฑํ๋ค.
๐ก ์ค์ํํธ์ ํ์ ์บ์คํ
- ์ธ์คํด์ค์ ํ์ ํ์ธ
- ์์ ์ ๋ค๋ฅธ ํ์ ์ ์ธ์คํด์ค์ธ์ ํ์ธํ๊ธฐ
1๏ธโฃ ์ธ์คํด์ค์ ํ์ ํ์ธ: as
์ธ์คํด์ค๊ฐ ํด๋น ํด๋์ค์ ์ธ์คํด์ค๋ผ๋ฉด true ๋ฐํ
์๋๋ผ๋ฉด false ๋ฐํ
// ๋ถ๋ชจ ํด๋์ค ์์ฑ class Flower { var name: String init(name: String) { self.name = name } var description: String { return "This flower is \(name)" } } // ์์ ํด๋์ค-1 ์์ฑ class Freesia:Flower { var color: String override var description: String { return "This flower is \(name) and color is \(color)" } init(color: String, name: String){ self.color = color super.init(name: name) } } // ์์ ํด๋์ค-2 ์์ฑ class Rose:Flower { var season: String override var description: String { return "This flower is \(name) and It blooms in May-June" } init(season: String, name: String){ self.season = season super.init(name: name) } } // ์ธ์คํด์ค ์์ฑ let flower:Flower = Flower(name: "cherryBlossom") print(flower.name) // cherryBlossom let myFavor:Freesia = Freesia(color: "yellow", name: "Freesia") print(myFavor.description) // This flower is Freesia and color is yellow let yourFavor:Rose = Rose(season: "Spring", name: "Rose") print(yourFavor.description) // This flower is Rose and It blooms in May-June // is: ๋ฐ์ดํฐ ํ์ ํ์ธ print(flower is Flower) //true print(flower is Freesia) //false print(flower is Rose) //false
2๏ธโฃ ๋ค์ด์บ์คํ
๋ถ๋ชจ ํด๋์ค์ ํ์ ์ ์์ ํด๋์ค์ ํ์ ์ผ๋ก ์บ์คํ ํ๋ค
์์ ์ฝ๋์์ Flower์ ๋ถ๋ชจ ํด๋์ค์ด๊ณ , Rose๋ ์์ ํด๋์ค์ผ ๋
Flower -> Rose : ์ ์บ์คํ (ํญ์ ์ฑ๊ณต)
Rose -> Flower: ๋ค์ด์บ์คํ (์คํจ ๊ฐ๋ฅ์ฑ์ด ์๊ธฐ ๋๋ฌธ์ ์กฐ๊ฑด๋ถ ์ฐ์ฐ์ as?๋ฅผ ์ฌ์ฉํ๋ ๊ฒ์ด ์ข๋ค)// as: ๋ค์ด ์บ์คํ if let givingFlower: Freesia = flower as? Freesia { print("This is yours") } else { print(flower.description) } // ๊ฒฐ๊ณผ : This flower is cherryBlossom if let givingFlower: Rose = yourFavor as? Rose { print("This is yours") } else { print(yourFavor.description) } // ๊ฒฐ๊ณผ : This is yours // yourFavor์ด ์ฐธ์กฐํ๋ ์ธ์คํด์ค๊ฐ Rose ํ์ ์ ์ธ์คํด์ค๋ผ๋ฉด givingFlower์ด๋ผ๋ ์์ ์์์ ํ ๋นํ๋ผ๋ ๋ป
์ฐธ๊ณ )
ํ์ ์บ์คํ (Type Casting) - The Swift Language Guide (ํ๊ตญ์ด)
library๊ฐ ๊ฐ๊ณ ์๋ Movie,Song์ธ์คํด์ค์ ๊ณตํต ๋ถ๋ชจ๋ MediaItem์ด๊ธฐ ๋๋ฌธ์ library๋ ํ์ ์ถ๋ก ์ ์ํด [MediaItem] ๋ฐฐ์ด์ ํ์ ๊ฐ๊ฒ ๋ฉ๋๋ค. library๋ฅผ ์ํ(iterate)ํ๋ฉด ๋ฐฐ์ด์ ์์ดํ ์ Movie, Song ํ์ ์ด
jusung.gitbook.io
'iOS > Swift' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Swift] ๊ฐ์ฒด ์งํฅ ํ๋ก๊ทธ๋๋ฐ (0) 2022.09.01 [Swift] ํ๋กํ ์ฝ(protocol) (0) 2022.08.31 [Swift] ์์ (Inheritance) (0) 2022.08.22 [Swift] ์๋ธ์คํฌ๋ฆฝํธ(subscript) (0) 2022.08.20 [Swift] ๋ชจ๋๋(Monad) (0) 2022.08.15