Swift3不仅移除了swift2中的部分特性,同时也增加了自己的新特性
1.内联序列函数sequence
Swift 3新增了两个全局函数:sequence(first: next:)和sequence(state: next:)。使用它们可以返回一个无限序列。下面是一个简单的使用样例
//从某一个树节点一直向上遍历到根节点
fornode insequence(first: leaf, next: { $0.parent }) {
// node is leaf, then leaf.parent, then leaf.parent.parent, etc.
}
//遍历出所有的2的n次方数(不考虑溢出)
forvalue insequence(first: 1, next: { $0 * 2 }) {
// value is 1, then 2, then 4, then 8, etc.
}
2.key-path不再只能使用String
这个是用在键值编码(KVC)与键值观察(KVO)上的
我们还是可以继续使用String类型的key-Path
//用户类
classUser: NSObject{
varname:String= ""//姓名
varage:Int= 0 //年龄
}
//创建一个User实例对象
letuser1 = User()
user1.name = "hangge"
user1.age = 100
//使用KVC取值
letname = user1.value(forKey: "name")
print(name)
//使用KVC赋值
user1.setValue("hangge.com", forKey: "name")
但建议使用新增的#keyPath()写法,这样可以避免我们因为拼写错误而引发问题。
//使用KVC取值
letname = user1.value(forKeyPath: #keyPath(User.name))
print(name)
//使用KVC赋值
user1.setValue("hangge.com", forKeyPath: #keyPath(User.name))
3.Foundation去掉NS前缀
比如过去我们使用Foundation相关类来对文件中的JSON数据进行解析,这么写:
letfile = NSBundle.mainBundle().pathForResource("tutorials", ofType: "json")
leturl = NSURL(fileURLWithPath: file!)
letdata = NSData(contentsOfURL: url)
letjson = try! NSJSONSerialization.JSONObjectWithData(data!, options: [])
print(json)
在Swift 3中,将移除NS前缀,就变成了:
letfile = Bundle.main.path(forResource: "tutorials", ofType: "json")
leturl = URL(fileURLWithPath: file!)
letdata = try! Data(contentsOf: url)
letjson = try! JSONSerialization.jsonObject(with: data)
print(json)