swift语言点评十九-类型转化与检查

Posted zzfx

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 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语言点评十九-类型转化与检查的主要内容,如果未能解决你的问题,请参考以下文章

swift语言点评二

苹果新的编程语言 Swift 语言进阶(十三)--类型检查与类型嵌套

swift语言点评十七-Designated Initializers and Convenience Initializers

swift语言点评四-Closure

swift语言点评三 - Basic Operators

swift语言点评十二-Subscripts