[Udemy iOS & Swift Bootcamp] Type Casting
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