[Swift] Day12: type conversion, swiftday12
Type Conversion Type Determination
We can useisTo determine whether an instance belongs to a specified class or its subclass. The function is similarOCInisKindOfClass.
Here is a simple example:
class A {}class B: A {}class C: A {}var array = [B(),A(),C(),A()] // [A]for item in array { if item is B { println("B") // 1 time } if item is C { println("C") // 1 time } if item is A { // ERROR! ALWAYS TRUE println("C") // 1 time }}Downward Transformation
You can use the type conversion operator.asTry to convert an instance to its subtype. The conversion does not actually change the instance or its value. The underlying potential Instance remains unchanged, but simply uses it as the class it is converted.
For example, the following code:
class A {}class B: A {}class C: A {}var array = [B(),A(),C(),A()] // [A]for item in array { if let aB = item as? B { println("aB") // 1 time } if let aC = item as? C { println("aC") // 1 time }}Any And AnyObject
Swift provides two special types of aliases for uncertain types:
- Any can represent Any type, except function types ).
- AnyObject can represent any class type instance.
References