At the request of netizens, I have summed up the following as, as!, as? The similarities and differences of these three types of conversion operators, as well as their respective usage scenarios.
1,as Use Occasion
(1) Convert from derived class to base class, transition upward (upcasts)
Class Animal {}
Class Cat:animal {}
Let cat = Cat ()
Let animal = cat as Animal
(2) Elimination of ambiguity, numeric type conversion
Let NUM1 = CGFloat
Let num2 = ' as Int '
Let num3 = 42.5 as Int
Let num4 = (42/2) as Double
(3) Pattern matching in switch statements
If you do not know what type of object is, you can detect its type by switch syntax and try to handle it in different situations using the corresponding type.
Switch Animal {
Case let Cat as Cat:
Print ("If it is a cat type object, do it appropriately")
Case let dog as dog:
Print ("If it is a dog type object, do the appropriate processing")
Default:break
}
2,as! Use Occasion
The downward Transition (downcasting) is used. Because it is mandatory type conversion, a runtime run error is reported if the conversion fails.
Class Animal {}
Class Cat:animal {}
Let Animal:animal = Cat ()
Let cat = Animal as! Cat
3,as? Use occasion
As? and as! The conversion rules for operators are exactly the same. But as? If the conversion is unsuccessful, a nil object is returned. Successful words return the optional type value (optional), which we need to split the package to use.
Because as? There is no error when the conversion fails, so you can use as! if you are sure that 100% will succeed, otherwise use as?
Let Animal:animal = Cat ()
If let cat = animal as? cat{
Print ("Cat is not nil")
} else {
Print ("Cat is nil")
}
Original: www.hangge.com