πŸ“± 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