๐Ÿ“ฑ App Development Study/iOS๐ŸŽ

[Udemy iOS & Swift Bootcamp] Type Casting

ibelieveinme 2023. 7. 2. 02:29
728x90

Type casting ์— ์‚ฌ์šฉ๋˜๋Š” ๊ตฌ๋ฌธ์„ ์•Œ์•„๋ณด์ž.

 

is

๋ฐ์ดํ„ฐ ํƒ€์ž… ํ™•์ธ์šฉ

let cell = UITableViewCell()

if cell is UITableViewCell {
    print("The types match!")
}

as?

๋‹ค์šด์บ์ŠคํŒ…์„ ํ™•์ธํ•˜๊ณ  ๋ณ€ํ™˜ํ•˜๋Š” ๊ฒƒ. ์ฃผ๋กœ if ๋ฌธ๊ณผ ํ•จ๊ป˜ ์‚ฌ์šฉํ•จ.

if let messageCell = cell as? MessageCell {
	//Then can use messageCell's capabilities
}

as!

๋ฐ์ดํ„ฐ ํƒ€์ž…์„ ์„œ๋ธŒ ํด๋ž˜์Šค๋กœ ๋ณ€ํ™˜

๊ฐ•์ œ ๋‹ค์šด ์บ์ŠคํŒ…. Forced Downcast

let messageCell = cell as! MessageCell

as 

ํƒ€์ž…์„ ์Šˆํผ ํด๋ž˜์Šค๋กœ ๋ฐ”๊พธ๋Š”, ํ•ญ์ƒ ์˜ณ์€ Upcast

let newCell = messageCEll as UITableViewCell

Object ์˜ ๋ฐ์ดํ„ฐ ํƒ€์ž…์„ ์•Œ์•„๋ณด์ž.

 

Any (All obejcts) > AnyObject (Objects derived from classes) > NSObject (Foundation objects) ์ˆœ์œผ๋กœ ํฌํ•จ๋œ๋‹ค.

 

์ฐธ๊ณ ๋กœ Swift ์—์„œ String, Int ์˜ ๊ธฐ๋ณธํƒ€์ž…์€ Struct ์ด๋‹ค. 

์ฆ‰ let objectTests: [Any] = [Int, String, String] ์€ ๊ฐ€๋Šฅํ•œ๋ฐ

let obejctsTests: [AnyObject] = [Int, Stirng, String] ์€ ๋ถˆ๊ฐ€๋Šฅํ•˜๋‹ค.

 

Any

๋ชจ๋“  ํƒ€์ž…์˜ ์ธ์Šคํ„ด์Šค๋ฅผ ๋‚˜ํƒ€๋‚ผ ์ˆ˜ ์žˆ๋‹ค.

 

AnyObject

๋ชจ๋“  ํด๋ž˜์Šค ํƒ€์ž…์˜ ์ธ์Šคํ„ด์Šค๋ฅผ ๋‚˜ํƒ€๋‚ผ ์ˆ˜ ์žˆ๋‹ค.

 

NSObject

Object์˜ ์ตœ์ƒ๋‹จ ๋ฃจํŠธ ํด๋ž˜์Šค.


https://docs.swift.org/swift-book/documentation/the-swift-programming-language/typecasting/

 

Documentation

 

docs.swift.org

 

728x90