rivate、open。它们可以看成是对原来 private 和 public 的进一步细分。具体使用方法和介绍可以看我写的另一篇文章:Swift - Swift3新增的两个访问控制关键字介绍(fileprivate、open) 三、一些语法的修改
1、数组排序:sort()与sorted()
过去数组排序的两个方法:sortInPlace() 和 sort(),现在分别改名成 sort() 和 sorted()
sort() 是直接对目标数组进行排序。sorted() 是返回一个排序后的数组,原数组不变。
var array1 = [1, 5, 3, 2, 4]
array1.sort()
print(array1) //[1, 2, 3, 4, 5]
var array2 = [1, 5, 3, 2, 4]
let sortedArray = array2.sorted()
print(array2) //[1, 5, 3, 2, 4]
print(sortedArray) //[1, 2, 3, 4, 5]
2、reversed()与enumerated()
过去 reverse() 方法实现数组反转,enumerate() 方法实现遍历。现这两个方法都加上 ed 后缀(reversed、enumerated)
for i in (1...10).reversed() {
print(i)
}
let array = [1, 5, 3, 2, 4]
for (index, value) in array.enumerated() {
print("\(index + 1) \(value)")
}
3、CGRect、CGPoint、CGSize
过去的 CGRectMake、CGPointMake、CGSizeMake 已废弃。现改用 CGRect、CGPoint、CGSize 代替。
//Swift 2
let frame = CGRectMake(0, 0, 20, 20)
let point = CGPointMake(0, 0)
let size = CGSizeMake(20, 20)
//Swift 3
let frame = CGRect(x: 0, y: 0, width: 20, height: 20)
let point = CGPoint(x: 0, y: 0)
let size = CGSize(width: 20, height: 20)
4、移除了API中多余的单词
- XCPlaygroundPage.currentPage 改为 PlaygroundPage.current
- button.setTitle(forState) 改为 button.setTitle(for)
- button.addTarget(action, forControlEvents) 改为 button.addTarget(action, for)
- arr.minElement() 改为 arr.min()
- arr.maxElement() 改为 arr.max()
- attributedString.appendAttributedString(anotherString) 改为 attributedString.append(anotherString)
- names.insert("Jane", atIndex: 0) 改为 names.insert("Jane", at: 0)
- NSBundle.mainBundle() 改为 Bundle.main
- UIDevice.currentDevice() 改为 UIDevice.current
- NSData(contentsOfURL) 改为 Data(contentsOf)
- NSJSONSerialization.JSONObjectWithData() 改为 JSONSerialization.jsonObject(with)
- UIColor.blueColor() 改为 UIColor.blue
5、枚举成员变成小写字母开头
Swift 3 将枚举成员当做属性来看,所以现在使用小写字母开头而不是以前的大写字母。
.system //过去是:.System
.touchUpInside //过去是:.TouchUpInside
.fillStroke //过去是:.FillStroke
.cgColor //过去是:.CGColor
6、@discardableResult
在 Swift 3 中,如果一个方法有返回值。而调用的时候没有接收该方法的返回值,Xcode 会报出警告,告诉你这可能会存在潜在问题。
除了可以通过接收返回值消除警告。还可以通过给方法声明 @discardableResult 来达到消除目的。
.system //过去是:.System
.touchUpInside //过去是:.TouchUpInside
.fillStroke //过去是:.FillStroke
.cgColor //过去是:.CGColor
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
printMessage(message: "Hello Swift 3!")
}
@discardableResult
func printMessage(message: String) -> String {
let outputMessage = "Output : \(message)"
return outputMessage
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
原文出自:航歌网