swift3.0都改变了什么
经历了从swift 1.0 到2.0,一个版本之后代码居然就不兼容了。这如何在团队推广呢?没有想到3.0居然变化更加的大。有多大,来体会一下: UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline) UIFont.preferredFont(forTextStyle: UIFontTextStyleSubheadline) override func numberOfSectionsInTableView(tableView: UITableView) -> Int override func numberOfSections(in tableView: UITableView) -> Int 在swift 2.x的时代基本上ObjC的接口是什么样的,那么swift的方法名称也是一样的。 在swift发布的时候,其实很多人都发现其语法有很多脚本语言的特征。但是方法名称还是保留着ObjC的“见名知义”的特征,那叫一个长,把这个方法的功能里里外外都说明的非常清楚。但是,其实这些没有完全的必要。所以在swift 3.0里使用方法里参数的lable来完成说明方法功能的作用。 去掉多余文字所谓“去掉多余文字”就是把原来iOS SDK方法名称里的描述性文字都移到方法的label里面。并且原来方法第一个参数的label可以不写的,现在所有label在调用的时候都需要给出,除非特殊说明。这样的修改就大大的缩短了方法名。 attributedString.appendAttributedString(anotherString) attributedString.append(anotherString) names.insert("Jane",atIndex: 0) names.insert("Jane",at: 0) UIDevice.currentDevice() UIDevice.current() 第一个参数的label如上所述,方法的第一个参数的label在swift2.x版本里调用的时候是不用写的,但是在3.0版本必须给出。 NSTimer.scheduledTimerWithTimeInterval(0.35,target: self,selector: #selector(reset),userInfo: nil,repeats: true) NSTimer.scheduledTimer(timeInterval: 0.35,repeats: true) 如果说你在自己定义的方法在调用的时候不需要label,那么需要显式的用下划线“_”表明。 override func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int { ... } override func didMoveToView(_ view: SKView) { ... } 对SDK里C的改造这是千呼万唤始出来的修改。之前对于c接口的调用基本上保持了和ObjC调用一致的风格: let ctx = UIGraphicsGetCurrentContext() let rectangle = CGRect(x: 0,y: 0,width: 512,height: 512) CGContextSetFillColorWithColor(ctx,UIColor.blueColor().CGColor) CGContextSetStrokeColorWithColor(ctx,UIColor.whiteColor().CGColor) CGContextSetLineWidth(ctx,10) CGContextAddRect(ctx,rectangle) CGContextDrawPath(ctx,.FillStroke) UIGraphicsEndImageContext() 在swift3.0中也改造成了swift风格的API: if let ctx = UIGraphicsGetCurrentContext() { let rectangle = CGRect(x: 0,height: 512) ctx.setFillColor(UIColor.blue().cgColor) ctx.setStrokeColor(UIColor.white().cgColor) ctx.setLineWidth(10) ctx.addRect(rectangle) ctx.drawPath(using: .fillStroke) UIGraphicsEndImageContext() } 还有GCD部分的API也已经改造。GCD是完全用C写的一个叫做libdispatch的库。在swfit3.0中是这样的: let queue = DispatchQueue(label: "com.test.myqueue") queue.async { print("Hello World") } 与之前的调用方式差别很大,之前是这样的: let queue = dispatch_queue_create("com.test.myqueue",nil) dispatch_async(queue) { print("Hello World") } 方法类型在一个方法可以接受另外一个方法作为参数传入的时候,这个方法的定义在swift2.0里是这样的: func g(a: Int -> Int) -> Int -> Int { ... }
func g(a: (Int) -> Int) -> (Int) -> Int { ... } 更加易读。至少能看出来接受一个Int型参数了。 最后以上是一些经常会接触到的改变。其他的改变还有性能的提升,和编译后APP提及的缩减。这些不是一眼能看见的改变也是非常的巨大的。但是,更加有魅力也更加实用的改变是 另外还有很重要的一点。swift已经发展到一定的程度,语言本身已经基本定型。所以从这个版本开始swift社区把代码的兼容放在一个比较靠前的位置来考虑了。至少按照官方的说法是不到万不得已不破坏代码的向前兼容(最前也就到swift3.0了)。可以考虑在在团队中引入swift了。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |