Swift 2.3 升级 Swift 3.0 我遇到的坑

首先是要使用Xcode8,系统在10.11.5以上,闲着没事用2.3写项目玩,然后3.0也出来一会儿了,就想着升级玩,然后就只改错误,改错误……

改了整整一个下午………………



如果你遇到程序启动之后就黑屏,还不走Appdelegate方法,那么你可能需要把

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {}

替换

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {}

不要忽略警告,少个参数都不能进去方法 比如 _ 这个

字典:

2.3
let dict = [String : AnyObject]

3.0
let dict = [String : Any]


去掉NS 比如:NSDate → Date


监听通知

2.3 
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AppDelegate.changeRootController(_:)), name: PQChangeRootViewControllerKey, object: nil)


3.0 
NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.changeRootController(noti:)), name: NSNotification.Name(rawValue: PQChangeRootViewControllerKey), object: nil)


发送通知

2.3 
NSNotificationCenter.defaultCenter().postNotificationName(PQChangeRootViewControllerKey, object: true)

3.0
NotificationCenter.default.post(name: NSNotification.Name(rawValue: PQChangeRootViewControllerKey), object: true)

移除

2.3
NSNotificationCenter.defaultCenter().removeObserver(self)

3.0
NotificationCenter.default.removeObserver(self)

简化 CG...

2.3
CGRectZero
CGPointZero
CGSizeZero


3.0
CGRect.zero
CGPoint.zero
CGSize.zero

删除Make
2.3
CGPointMake(.....)

3.0
CGPoint(...)

UIColor

2.3
UIColor.redColor()

3.0
UIColor.red

去掉方法多余参数 必须写上第一个参数label

2.3
func encodeWithCoder(aCoder: NSCoder){...}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {}


3.0
func encode(with aCoder: NSCoder) {...}
override func setValue(_ value: Any?, forUndefinedKey key: String) {}

方法返回值

Swift 3.0 中方法的返回值必须有接收否则会报警告,但是有些情况下确实不需要使用返回值可以使用"_"接收来忽略返回值。当然你也可以增加@discardableResult 声明,告诉编译器此方法可以不用接收返回值。

协议可选方法

在Swift3.0之前如果要定义协议中可选方法,只需要给协议加上@objc之后方法使用optional修饰就可以了,但是Swift3.0中除了协议需要@objc修饰,可选方法也必须使用@objc来修饰。

@objc protocol MyProtocol { 
   @objc optional func func1() //old: optional func 
   func1() func func2()
}

截取字符串:

let codeStr = "abc="
let url = URL(string: "http://sdfdsff.com/request?name=dfsdafd&password=sdfsdf35eyre9?abc=sdf34dsfs")

2.3
let code = url!.query?.substring(to: codeStr.endIndex)

3.0
let code = url!.query?.substring(from: codeStr.endIndex)

enum 第一个字母小写

2.3 设置按钮的标题
..... forState: .Normal

3.0
..... for: .normal

根据服务器返回的数据强制解包

2.3
let name = JSON["name"] as String

3.0
let result = JSON as! [String : Any]
let name = result["name"] as String

或者写在一行里面
let name = (JSON as! [String :Any])["name"] as String

Bool 类型属性

2.3
button.hidden = fasle

3.0
button.isHidden = false

简写

2.3 
UIScreen.mainScreen().bounds

3.0
UIScreen.main.bounds

有点乱,持续更新...

你可能感兴趣的:(Swift 2.3 升级 Swift 3.0 我遇到的坑)