swift語言點評十九-類型轉化與檢查
1、oc比較:
-(BOOL) isKindOfClass: classObj判斷是否是這個類或者這個類的子類的實例
-(BOOL) isMemberOfClass: classObj 判斷是否是這個類的實例
2、is 類型檢查
Use the type check operator (is
) to check whether an instance is of a certain subclass type.
3、 (as?
or as!
) 類型轉化
Use the conditional form of the type cast operator (as?
) when you are not sure if the downcast will succeed.
Use the forced form of the type cast operator (as!
) only when you are sure that the downcast will always succeed.
確信與不確信轉化。
4、Type Casting for Any and AnyObject
Swift provides two special types for working with nonspecific types:
-
Any
can represent an instance of any type at all, including function types. -
AnyObject
can represent an instance of any class type.
To discover the specific type of a constant or variable that is known only to be of type Any
or AnyObject
, you can use an is
or as
pattern in a switch
statement’s cases. The
The Any
type represents values of any type, including optional types. Swift gives you a warning if you use an optional value where a value of type Any
Any
value, you can use the as
operator to explicitly cast the optional to Any
, as shown below.
let optionalNumber: Int? = 3
things.append(optionalNumber) // Warning
things.append(optionalNumber as Any) // No warning
swift語言點評十九-類型轉化與檢查