Swift 3.0 中的新变化
本文翻译自 www.hackingwithswift.com 上发布的英文文章,原文链接What’s new in Swift 3.0 提前警告 #1: 有很多的变动看起来可能是很琐碎的,我们希望的是这些变化是一次性的,使这门语言在将来的几年里趋于稳定,同时也意味着将来的变动会更小。 所有的函数参数都有标签了,除非你要求去掉我们调用函数和方法的方式在 Swift 2.0 时就已经变动过了,但这次又变了,而且这一次将会把所有的都破坏掉。在 Swift 2.x 及以前,方法名的第一个参数不需要写标签,所以第一个参数的标签通常会写到方法名上。例如: names.indexOf("Taylor")
"Taylor".writeToFile("filename",atomically: true,encoding: NSUTF8StringEncoding)
SKAction.rotateByAngle(CGFloat(M_PI_2),duration: 10)
UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
override func numbeOfSectionsInTableView(tableView: UITableView) -> Int
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView?
NSTimer.scheduledTimerWithTimeInterval(0.35,target: self,selector: #selector(createEnemy),userInfo: nil,repeats: true)
除非你明确指定,否则 Swift 3 中所有的参数都会有标签,也就意味着方法名不再描述它们的参数了。在实际中,这通常意味着方法名的最后一部分要变成第一个参数的名字。 names.indexOf("Taylor")
names.index(of: "Taylor")
"Taylor".writeToFile("filename",atomically: true,encoding: NSUTF8StringEncoding)
"Taylor".wirte(toFile: "filename",encoding: NSUTF8StringEncoding)
SKAction.rotateByAngle(CGFloat(M_PI_2),duration: 10)
SKAction.rotate(byAngle: CGFloat(M_PI_2),duration: 10)
UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
UIFont.preferredFont(forTextStyle: UIFontTextStyleSubheadline)
override func numberOfSectionInTableView(table: UITableView) -> Int
override func numberOfSection(in tableView: UITableView) -> Int
NSTimer.scheduledTimerWithTimeInterval(0.35,target: self,repeats: true)
NSTimer.scheduledTimer(timeInterval: 0.35,repeats: true)
这些是你要调用的方法,但是,当连续调用多个方法时还会有一个连锁反应:当连接上诸如 UIKit 一类的框架,即使在 Swift 3 中它们依然会遵循没有第一个参数标签的旧风格。 override func viewWillAppear(animated: Bool)
override func tableView(tableView: UITableView,numberOfRowsInSection section: Int) -> Int
override func didMoveToView(view: SKView)
override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?)
func textFieldShouldReturn(textField: UITextField) -> Bool
在 Swift 3 里,都需要在第一个参数前面加一个下划线,来告诉调用方(Objective-C 代码)不会使用参数标签: override func viewWillAppear(_ animated: Bool)
override func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int
override func didMoveToView(_ view: SKView)
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?)
func textFieldShouldReturn(_ textField: UITextField) -> Bool
省略不必要的单词当 Swift 在 2015 年 12 月开源时,它那崭新的 API 指南里有这么一段:”省略不必要的单词(omit needless words)”。这也引入了 Swift 3 中另一个巨大的改动,因为这意味着方法名中包含的不言而喻的单词现在已经移除了。 let blue = UIColor.blueColor()
let min = numbers.minElement()
attributedString.appendAttributedString(anotherString)
names.insert("Jane",atIndex: 0)
UIDevice.currentDevice()
你能找出其中不必要的单词吗?当使用 let blue = UIColor.blue()
let min = numbers.min()
attributedString.append(anotherString)
names.insert("Jane",at: 0)
UIDevice.current()
正如你所见,这让方法名明显变短了! " Hello ".stringByTrimingCharactersInset(.whitespaceAndNewlineCharacterSet())
" Hello ".trimingCharacters(in: .whitespaceAndNewlines)
"Taylor".containsString("ayl")
"Taylor".contains("ayl")
"1,2,3,4,5".componentsSeparatedByString(",")
"1,5".components(separatedBy: ",")
myPath.stringByAppendingPathComponent("file.txt")
myPath.appendingPathComponent("file.txt")
"Hello,world".stringByReplacingOccurrencesOfString("Hello",withString: "Goodbye")
"Hello,world".replacingOccurrences(of: "Hello",with: "Goodbye")
"Hello,world".substringFromIndex(7)
"Hello,world".substring(from: 7)
"Hello,world".capitalizedString
"Hello,world".capitalized
注意: dismiss(animated: true,completion: nil)
我第一次看到它时,我懵了:”dismiss 什么?”,这差不多就是适应了 iOS 编程这么久后不可避免的斯德哥尔摩综合正的表现,但是一旦你学会调换参数标签变化,重新添加不必要的单词,就会看到它等效的 Swift 2.2 代码: dismissViewControllerAnimated(true,completion: nil)
实际上 dismiss(animated: true)
同样的变化也发生在了 override func prepare(for segue: UIStoryboardSegue,sender: AnyObject?)
枚举属性的大驼峰现在替换成了小驼峰虽然语法上无关紧要,我们用来命名类、结构体、属性、枚举的大写字母一直大体上遵循这样的惯例:类、结构体和枚举用大驼峰(MyStruct,WeatherType.Cloudy),属性和参数名用小驼峰(emailAddress, requestString)。 let red = UIColor.red.cgColor
这些变化确实有助于提高一致性:所有的属性和参数都需要没有例外的由小写字母开头。 UIInterfaceOrientationMask.Portrait // 旧的
UIInterfaceOrientationMask.portrait // 新的
NSTextAlignment.Left // 旧的
NSTextAlignment.left // 新的
SKBlendMode.Replace // 旧的
SKBlendMode.replace // 新的
你懂了吧。然而,这个小变化还带来了一些更大的改动,由于 Swift 的可选类型在底层实际上就是一个枚举,就像这样: enum Optional {
case None
case Some(Wrapped)
}
这意味着,如果你用过 for case let .some(datum) in data { print(datum) }
for case let datum? in data { print(datum) }
C 函数的 Swift 风格引入Swift 3 里引入了针对 C 函数的特性来让库作者们指定他们的代码引入到 Swift 中新的优雅方式。例如,所有以 “CGContext”开头的函数现在映射到了一个 CGContext 对象的成员方法,使其更符合 Swift 的语言习惯,是的,这意味着像 let ctx = UIGraphicsGetCurrentContext()
let rectangle = CGRect(x: 0,y: 0,width: 512,height: 512)
CGContextSetFillColorWithColor(ctx,UIColor.redColor().CGColor)
CGContextSetStrokeColorWithColor(ctx,UIColor.blackColor().CGColor)
CGContextSetLineWidth(ctx,10)
CGContextAddRect(ctx,rectangle)
CGContextDrawPath(ctx,.FillStroke)
UIGraphicsEndImageContext()
Swift 3 里, if let ctx = UIGraphicsGetCurrentContext() {
let rectangle = CGRect(x: 0,height: 512)
ctx.setFillColor(UIColor.red.cgColor)
ctx.setStrokeColor(UIColor.black.cgColor)
ctx.setLineWidth(10)
ctx.addRect(rectangle)
ctx.drawPath(using: .fillStroke)
UIGraphicsEndImageContext()
}
注意:在 Swift 2.2 和 Swift 3.0 CGAffineTransformIdentity
CGAffineTransform.identity
CGAffineTransformMakeScale(2,2)
CGAffineTransform(scaleX: 2,y: 2)
CGAffineTransformMakeTranslation(128,128)
CGAffineTransform(translationX: 128,y: 128)
CGAffineTransformMakeRotation(CGFloat(M_PI))
CGAffineTransform(rotationAngle: CGFloat(M_PI))
动词和名词这一部分人们会开始有些困惑,但这确实很重要的部分。 myArray.enumerate()
myArray.enumerated()
myArray.reverse()
myArray.reversed()
每一次 Swift 3 里在方法名里追加一个 ‘d’:这就是一个被返回的值。 这些改动是为了什么?这些改动都容易看懂,其中一些的改动很细微但是造成的破坏却是严重的,可以想象苹果的 Swift 工程师只是让我们的生活更艰难了。然而,事实是他们在非常努力的让 Swift 变得易学、易用并且尽可能地快,这是他们的首要任务。特别是,我已经被苹果团队所承诺的作为社区努力的一部分,确保他们所做的改动都是经过公开讨论并同意的而打动了。上面所说的每一个变化都经过了社区大范围的讨论才可以加入到 Swift 3.0,这绝对是一件不可思议的事。 你也可以参与进来帮助改进这些变化,他们热衷于听取广大用户的想法,这也意味着 Swift 的未来真的在你的手中 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |