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

本文介绍了Swift中的类型检查与类型转换方法,包括使用is关键字进行类型检查,使用as?和as!操作符进行类型转换,并解释了确信与不确信转化的区别。此外还讲解了如何处理Any和AnyObject类型的值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值