Type conversion type judgment
We can is
determine whether an instance belongs to a specified class or its subclasses, and functions like this OC
isKindOfClass
.
Let's demonstrate by a simple example:
Class A {}class b:a {}class c:a {}varArray = [B (), A (), C (), A ()]//[A] forIteminchArray {ifItem isB {println ("B")//1 time}ifItem isC {println ("C")//1 time}ifItem isA//error! Always TRUEprintln"C")//1 time}}
Down transformation
You can use the type conversion operator to as
try to convert an instance to its subtype. The conversion does not really change the instance or its value. The underlying root instance remains the same, simply using it as the class it is converted to.
For example, the following code:
classA {}classb:a {}classc:a {}varArray = [B (), A (), C (), A ()]//[A] forIteminchArray {if LetAB = Item as? B {println ("AB")//1 time}if LetAC = Item as? C {println ("AC")//1 time}}
Any and Anyobject
Swift provides two special types of aliases for indeterminate types:
- Any can represent any type except the method type (function types).
- Anyobject can represent instances of any class type.
References
[Swift] DAY12: Type Conversion