swift語言點評十九-類型轉化與檢查

來源:互聯網
上載者:User

標籤:log   int   SM   cte   nal   mem   ant   gpo   exp   

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 is expected. If you really do need to use an optional value as an Anyvalue, you can use the as operator to explicitly cast the optional to Any, as shown below.

  1. let optionalNumber: Int? = 3
  2. things.append(optionalNumber) // Warning
  3. things.append(optionalNumber as Any) // No warning

 

swift語言點評十九-類型轉化與檢查

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.