as,有保证的转换class Animal {}
class Cat: Animal {}
let cat = Cat()
let animal = cat as Animal
let num1 = 42 as CGFloat
let num2 = 42 as Int
let num3 = 42.5 as Int
let num4 = (42 / 2) as Double
switch animal {
case let cat as Cat:print("如果是Cat类型对象,则做相应处理")
case let dog as Dog:print("如果是Dog类型对象,则做相应处理")
default: break
}
as!,强转,向下转型(Downcasting)时使用。由于是强制类型转换,如果转换失败会报 runtime 运行错误,就像⚠️一样表示具有危险性class Animal {}
class Cat: Animal {}
let animal :Animal = Cat()
let cat = animal as! Cat
as?,as? 和 as! 操作符的转换规则完全一样,但如果转换不成功的时候便会返回一个 nil 对象,成功的话返回可选类型值(optional)let animal:Animal = Cat()if let cat = animal as? Cat{print("cat is not nil")
} else {print("cat is nil")
}
2014 年的 Apple WWDC 发布了强语言 swift ,必须要指定一个对象是否为空。为了迎合swift,OC中增加了 __nullable 和 ___nonnull 用于指定对象是否为空。OC没有可选类型(optional)的概念,Swift和OC混编的时候,Swift编译器并不知道一个Objective-C对象到底是optional还是non-optional,编译器会隐式地将OC的对象当成是non-optional。苹果在Xcode 6.3引入了一个Objective-C的新特性:nullability annotations。这一新特性的核心是两个新的类型注释:
__nullable表示对象可以是NULL或nil__nonnull表示对象不应该为空。当不遵循这一规则时,编译器就会给出警告,但程序还是能编译通过并运行。
在任何可以使用const关键字的地方都可以使用__nullable和__nonnull,不过这两个关键字仅限于使用在指针类型上。
在属性声明中,以下三种都可以:
@property (nonatomic, copy, nonnull) NSArray * items;
@property (nonatomic, copy) NSArray * __nonnull items;@property(nonatomic,strong,nullable) NSString * name;
@property(nonatomic,strong) NSString *_Nullable name;
@property(nonatomic,strong) NSString *__nullable name;
在方法的声明中,可以使用不带下划线的nullable和nonnull:
- (nullable id)itemWithName:(NSString * nonnull)name;
-
- (nullable NSString *)buyBook:(nullable NSString *)book;
- (NSString *__nullable)buyBook:( NSString *__nullable)book;
- (NSString *_Nullable)buyBook:( NSString *_Nullable)book;
类似于@objc可以针对单个属性或者方法或者整个类,也有nonnull区域设置(Audited Regions) 。在下面这两个宏之间的代码,所有简单指针对象都被假定为nonnull,因此我们只需要去指定那些nullable的指针
#define NS_ASSUME_NONNULL_BEGIN _Pragma("clang assume_nonnull begin")
#define NS_ASSUME_NONNULL_END _Pragma("clang assume_nonnull end")
为了安全起见,苹果还制定了几条规则:
__nullable id * __nonnull。NSError **通常是被假定为一个指向nullable NSError对象的nullable指针。null_resettable: get方法:不能返回为空,set方法可以为空
@property(nonatomic,strong,null_resettable) NSNumber * number;
null_unspecified:不确定是否为空,使用方式有三种
@property(nonatomic,strong) NSNumber *_Null_unspecified height;
@property(nonatomic,strong) NSNumber *__null_unspecified height;
@property(nonatomic,strong,null_unspecified) NSNumber * height;
上一篇:写风景的技巧有哪些
下一篇:求求你!适合朗诵的抒情文章