扩展阅读iOS Developer

Swift 4里的新东西

2017-06-26  本文已影响85人  豆志昂扬
let farm = Farm(name: "Old MacDonald's Farm",
                location: Location(latitude: 51.621648, longitude: 0.269273),
                animals: [.chicken, .dog, .cow, .turkey, .dog, .chicken, .cow, .turkey, .dog])
let payload: Data = try JSONEncoder().encode(farm)
do {
    let farm = try JSONDecoder().decode(Farm.self, from: payload)
    
    let coordinates = "\(farm.location.latitude, farm.location.longitude)"
} catch {
    // 处理反序列化错误
}
let star = "刘国梁"
let introString = """ 
马龙、
张继科、
樊振东、
许昕等
退赛为了支持自己的主教练: \(star) 
"""
  1. �新增针对 key-value 的keyPath编码的支持,从Objective-C过来的开发者对KeyPath应该不会感到陌生。 更多阅读
class Person {
    var name: String
    var friends: [Person] = []
    var bestFriend: Person? = nil
    init(name: String) {
        self.name = name
    }
}
var han = Person(name: "Han Solo")
var luke = Person(name: "Luke Skywalker")
luke.friends.append(han)
// �创建keyPath
let firstFriendsNameKeyPath = \Person.friends[0].name
let firstFriend = luke[keyPath: firstFriendsNameKeyPath] // "Han Solo"
// 等价于
luke[keyPath: \.friends[0].name] // "Han Solo"
// map
let abc: String = "abc"
_ = abc.map {
    print($0.description)
}
// filter
let filtered = abca.filter { $0 == "a" }
// reduce
let result = abc.reduce("1") { (result, c) -> String in
    return result + String(c)
}
let s = "Hello, World!"
let i = s.index(of: ",")!
//改善前
let greeting = s[s.startIndex..<i]
//改善后
let greeting = s[..<i]
let withComma = s[...i]
let location = s[i...]
//以下代码在Swift 4中将有编译错误。
struct Foo {
    private func bar() {}
}
extension Foo {
    private func bar() {}
}
// [UIControl & Shakeable]这种写法是不是很美?
protocol Shakeable{
    func shake()
}
extension UIButton:Shakeable{ /* ... */ }
extension UISlider:Shakeable{ /* ... */ }
func shakeEm(controls: [UIControl & Shakeable]) {
    for control in controls where control.state.isEnabled {
        control.shake()
    }

Swift 4更新中还包括了对内存的互斥访问,编译优化,@objc推断等。 总体来看,Swift 还是一门较为年轻的语言,希望未来在服务器开发,人工智能领域能有更大的发展机会。

推荐阅读
Uber 和 Swift重写项目的故事

更多

请关注豆志昂扬微信公众号获取更多内容:

上一篇下一篇

猜你喜欢

热点阅读