斯维夫特(Swift) blog

指出读一次swift
blog
来精通OC与swift不同以及swift版本变动细节

Untyped Collections

隐式桥接不存在了,需要采纳as,swift3导入的cocoa接受了Any/AnyHashable,由此对于集合也可以应用[AnyHashable:Any]

// Swift 2
struct State {
    var name: String
    var abbreviation: String
    var population: Int

    var asPropertyList: [NSObject: AnyObject] {
        var result: [NSObject: AnyObject] = [:]//也可以使用NSDictionary
        // Implicit conversions turn String into NSString here…
        result["name"] = self.name
        result["abbreviation"] = self.abbreviation
        // …and Int into NSNumber here.
        result["population"] = self.population
        return result
    }
}

let california = State(name: "California",
                       abbreviation: "CA",
                       population: 39_000_000)
NSNotification(name: "foo", object: nil,
               userInfo: california.asPropertyList)

// Swift 3
struct State {
    var name: String
    var abbreviation: String
    var population: Int

    // Change the dictionary type to [AnyHashable: Any] here...
    var asPropertyList: [AnyHashable: Any] {
        var result: [AnyHashable: Any] = [:]
        // No implicit conversions necessary, since String and Int are subtypes
        // of Any and AnyHashable
        result["name"] = self.name
        result["abbreviation"] = self.abbreviation
        result["population"] = self.population
        return result
    }
}
let california = State(name: "California",
                       abbreviation: "CA",
                       population: 39_000_000)
// ...and you can still use it with Cocoa API here
Notification(name: "foo", object: nil,
             userInfo: california.asPropertyList)

Nullability and Objective-C

实在对应的就是可选值

  • !表示非空
  • ?可空

The AnyHashable Type

Any类型可以享有其余项目,但是Dictionary、Set需要Hasble,AnyHashble是swift3提议的hashable的超类,任何一个可hash的类别都落实了Anyhashble协议,比如String、Int

AnyObject Member Lookup

Any没有AnyObject的搜寻行为艺术,因而无法动态的向Any发送音信,不过AnyObject可以,此时需要更换

// Swift 2
func foo(x: NSArray) {
    // Invokes -description by magic AnyObject lookup
    print(x[0].description)
}

// Swift 3
func foo(x: NSArray) {
    // Result of subscript is now Any, needs to be coerced to get method lookup
    print((x[0] as AnyObject).description)//也可以转换到你期望的指定类型as!NSOjbect
}

Creating Model Objects from Values Extracted from JSON

若是有个食堂的model

import Foundation

struct Restaurant {
    enum Meal: String {
        case breakfast, lunch, dinner
    }

    let name: String
    let location: (latitude: Double, longitude: Double)
    let meals: Set<Meal>
}

来自sever的JSON数据

{
    "name": "Caffè Macs",
    "coordinates": {
        "lat": 37.330576,
        "lng": -122.029739
    },
    "meals": ["breakfast", "lunch", "dinner"]
}

Literals in Playgrounds

Xcode7.1开始辅助字面量,紧要用来颜色、图片、文件

OC id -> Swift Any

优点,不需要手动装箱
使得OC API更加灵敏

OC Swift2 Swift3
id AnyObject Any
NSArray * [AnyObject] [Any]
NSDictionary * [NSObject:AnyObject] [AnyHashable:Any]
NSSet * Set<NSObject> Set<AnyHashable>

需要留意的而是swift2不再提供隐式转换,由此NS桥接的内需你显示转换

Overriding methods and conforming to protocols

命名符合OC的正规化,id->Any

// Swift 2
class Foo: NSObject, NSCopying {
    override func isEqual(_ x: AnyObject?) -> Bool { ... }
    func copyWithZone(_ zone: NSZone?) -> AnyObject { ... }
}

// Swift 3
class Foo: NSObject, NSCopying {
    override func isEqual(_ x: Any?) -> Bool { ... }
    func copy(with zone: NSZone?) -> Any { ... }
}

Use Whole Module Optimization to infer final on internal declarations.

internal默认的访问控制权限注明仅可以在模块可见。swift编译文件是模块独立的,不能确定internal阐明在不同的文本是否被重写了。可是如果全勤模块的优化是开启的,所有的模块同时编译、能够允许编译器将internal臆度它的可见性

public class ParticleModel {
    var point = ( x: 0.0, y: 0.0 )
    var velocity = 100.0

    func updatePoint(newPoint: (Double, Double), newVelocity: Double) {
        point = newPoint
        velocity = newVelocity
    }

    public func update(newP: (Double, Double), newV: Double) {
        updatePoint(newP, newVelocity: newV)
    }
}

var p = ParticleModel()
for i in stride(from: 0.0, through: times, by: 1.0) {
    p.update((i * sin(i), i), newV:i*1000)
}

Writing a JSON Initializer with Error Handling

enum SerializationError: Error {
    case missing(String)
    case invalid(String, Any)
}

extension Restaurant {
    init(json: [String: Any]) throws {
        // Extract name
        guard let name = json["name"] as? String else {
            throw SerializationError.missing("name")
        }

        // Extract and validate coordinates
        guard let coordinatesJSON = json["coordinates"] as? [String: Double],
            let latitude = coordinatesJSON["lat"],
            let longitude = coordinatesJSON["lng"]
        else {
            throw SerializationError.missing("coordinates")
        }

        let coordinates = (latitude, longitude)
        guard case (-90...90, -180...180) = coordinates else {
            throw SerializationError.invalid("coordinates", coordinates)
        }

        // Extract and validate meals
        guard let mealsJSON = json["meals"] as? [String] else {
            throw SerializationError.missing("meals")
        }

        var meals: Set<Meal> = []
        for string in mealsJSON {
            guard let meal = Meal(rawValue: string) else {
                throw SerializationError.invalid("meals", string)
            }

            meals.insert(meal)
        }

        // Initialize properties
        self.name = name
        self.coordinates = coordinates
        self.meals = meals
    }
}

Extracting Values from JSON

JSONSerialization类方法jsonObject再次来到Any类型并且扔出分外倘诺data不可以分析

import Foundation

let data: Data // received from a network request, for example
let json = try? JSONSerialization.jsonObject(with: data, options: [])

json顶层对象一般为字典或者数组,大家得以采取as?+if举行判断转换

// Example JSON with object root:
/*
    {
        "someKey": 42.0,
        "anotherKey": {
            "someNestedKey": true
        }
    }
*/
if let dictionary = jsonWithObjectRoot as? [String: Any] {
    if let number = dictionary["someKey"] as? Double {
        // access individual value in dictionary
    }

    for (key, value) in dictionary {
        // access all key / value pairs in dictionary
    }

    if let nestedDictionary = dictionary["anotherKey"] as? [String: Any] {
        // access nested dictionary values by key
    }
}

// Example JSON with array root:
/*
    [
        "hello", 3, true
    ]
*/
if let array = jsonWithArrayRoot as? [Any] {
    if let firstObject = array.first {
        // access individual object in array
    }

    for object in array {
        // access all objects in array
    }

    for case let string as String in array {
        // access only string values in array
    }
}

Interactive Playgrounds

关于那里可以去看本身的简文playground正确行使姿势

Infer final on declarations referenced in one file by applying the private keyword.

应用private关键字,限制在当前文件内,假如当前文件内没有对该class的重写,那么编译器就会臆度它不适用动态派发

class ParticleModel {
    private var point = ( x: 0.0, y: 0.0 )
    private var velocity = 100.0

    private func updatePoint(newPoint: (Double, Double), newVelocity: Double) {
        point = newPoint
        velocity = newVelocity
    }

    func update(newP: (Double, Double), newV: Double) {
        updatePoint(newP, newVelocity: newV)
    }
}

与final一样,private也能够修饰class

Working with JSON in Swift

JSONSerialization Foundation framework

Writing an Optional JSON Initializer

extension Restaurant {
    init?(json: [String: Any]) {
        guard let name = json["name"] as? String,
            let coordinatesJSON = json["coordinates"] as? [String: Double],
            let latitude = coordinatesJSON["lat"],
            let longitude = coordinatesJSON["lng"],
            let mealsJSON = json["meals"] as? [String]
        else {
            return nil
        }

        var meals: Set<Meal> = []
        for string in mealsJSON {
            guard let meal = Meal(rawValue: string) else {
                return nil
            }

            meals.insert(meal)
        }

        self.name = name
        self.coordinates = (latitude, longitude)
        self.meals = meals
    }
}

Swift Value Types in Objective-C

Any可以具备其它的结构体、枚举、元组或者此外的门类,OC的id在swift3等价于any,在swift2中需要手动封箱或者转入类,swift3则不需要

// Swift 2
struct CreditCard { number: UInt64, expiration: NSDate }

let PaymentMade = "PaymentMade"

// We can't attach CreditCard directly to the notification, since it
// isn't a class, and doesn't bridge.
// Wrap it in a Box class.
class Box<T> {
    let value: T
    init(value: T) { self.value = value }
}

let paymentNotification =
    NSNotification(name: PaymentMade,
                   object: Box(value: CreditCard(number: 1234_0000_0000_0000,
                                                 expiration: NSDate())))


// Swift 3
let PaymentMade = Notification.Name("PaymentMade")

// We can associate the CreditCard value directly with the Notification
let paymentNotification =
    Notification(name: PaymentMade,
                 object: CreditCard(number: 1234_0000_0000_0000,
                                    expiration: Date()))

亟待专注的是swift3中对此周边的布局体类型将会桥接作为透明对象而不是cocoa对象,Int、UInt、Double、Bool会桥接为NSNumber,Int8,UInt16则仅仅桥接为透明对象。要是赶上了unrecognized selector sent to _SwiftValue题材,它象征OC尝试唤醒一个艺术在swift
值类型上,此时我们需要手动管理

swift Any持有任一类型包括Optional,虽然OC api要求是nonull
id,Optional在未解包的场馆下也得以看作参数传递,会导致runtime
error而不是编译错误。swift3.0.1+Xoce8.1解决了上述问题,为了制止包容问题,不要借助于透明对象因为前景的swift可能会桥接到固定类型

Use final when you know that a declaration does not need to be overridden

final关键字可以范围class、method、property不被重写。可以安全的驱动编译器撤废动态派发。point、velocity、updatePoint不开展动态派发,直接访问,update举办动态派发

class ParticleModel {
    final var point = ( x: 0.0, y: 0.0 )
    final var velocity = 100.0

    final func updatePoint(newPoint: (Double, Double), newVelocity: Double) {
        point = newPoint
        velocity = newVelocity
    }

    func update(newP: (Double, Double), newV: Double) {
        updatePoint(newP, newVelocity: newV)
    }
}

final修饰类的时候,注明不可能被子类化,因而指明函数、属性都是final

final class ParticleModel {
    var point = ( x: 0.0, y: 0.0 )
    var velocity = 100.0
    // ...
}

Explicit Conversion for Unbridged Contexts

在有些限量的场地swift无法直接桥接C和OC的宏图,比如id*,这么些时候api将会呈现UnsafePointer<AnyObject>,此时亟需as转换,再&

// ObjC
@interface Foo

- (void)updateString:(NSString **)string;
- (void)updateObject:(id *)obj;

@end

// Swift
func interactWith(foo: Foo) -> (String, Any) {
    var string = "string" as NSString // explicit conversion
    foo.updateString(&string) // parameter imports as UnsafeMutablePointer<NSString>
    let finishedString = string as String

    var object = "string" as AnyObject
    foo.updateObject(&object) // parameter imports as UnsafeMutablePointer<AnyObject>
    let finishedObject = object as Any

    return (finishedString, finishedObject)
}

其它,OC的商事是类协议,不能够用结构体、枚举或其他轻量级的通用项目遵从OC的磋商

Increasing Performance by Reducing Dynamic Dispatch

swift允许重写超类的措施和性质,这就需要在运作时刻接的拜访并且实施直接调用。那一个技术叫做动态派发,这项技能扩充了语言表达的复杂性和大气的runtime消耗在直接的施用上。上面介绍二种方法消除动态派发:final、private、WholeModule
Optimization

请看上面的代码

class ParticleModel {
    var point = ( 0.0, 0.0 )
    var velocity = 100.0

    func updatePoint(newPoint: (Double, Double), newVelocity: Double) {
        point = newPoint
        velocity = newVelocity
    }

    func update(newP: (Double, Double), newV: Double) {
        updatePoint(newP, newVelocity: newV)
    }
}

var p = ParticleModel()
for i in stride(from: 0.0, through: 360, by: 1.0) {
    p.update((i * sin(i), i), newV:i*1000)
}

就像上边写的,编译器发出动态派发调用

  1. 调用p 的 update
  2. 调用p 的 updatePoint
  3. 得到p 的 point元祖属性
  4. 获取p 的 速率

此间使用动态派发的案由在于ParticleModel的子类可能通过可总计属性重写point、velocity,也重写update、updatePonit

动态派发调用的贯彻是透过搜寻method
table然后举办直接调用。着绝对于直接调用的快慢必然是慢的。

Strings in Swift 2

关于这里可以去看自己的简文您实在懂swift
string吗?