浅谈Swift编译检查

Swift编译检查

使用Swift进行编码时候, 编译器会自动检查Cocoa的方法是否符合开发的最低版本.

比如你在iOS8的项目中使用iOS10的一些API, 在编译期间就会被检查报错.

error: 'requestWhenInUseAuthorization()' is only available on iOS 10.0 or newer
            locationManager.requestWhenInUseAuthorization()
                            ^
note: add 'if #available' version check

你可以加入#available对不同系统版本执行不同代码

let locationManager = CLLocationManager()
if #available(iOS 10, OSX 10.10, *) {
    locationManager.requestWhenInUseAuthorization()
}else{

}

Objective-C编译检查

Objective-C不会在编译过程中对方法检查, 很有可能你在iOS8的项目调用iOS10的API, 然后就闪退了。这一点简直坑爹..
你要对方法进行判断是否可以响应, 可以响应则表示系统支持改版本.

let locationManager = CLLocationManager()
if locationManager.respondsToSelector("requestWhenInUseAuthorization") {
    locationManager.requestWhenInUseAuthorization()
}

你可能感兴趣的:(浅谈Swift编译检查)