3中的新特征

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 { ... }
}

fileprivate

在本来的swift中的private其实并不是当真的私人住房,如若二个变量定义为private,在同2个文书中的其余类照旧是足以访问到的。这么些地方在使用extension的时候很确定。

class User {
    private var name = "private"
}

extension User{
    var accessPrivate: String {
        return name
    }
}

如此那般拉动了四个难题:

  • 当大家标识为private时,意为真的私有照旧文件内可共享呢?
  • 当大家就算策动为确实的私人住房时,必须确定保证那几个类依然结构体在二个独自的文本里。否则大概同文件里别的的代码访问到。

透过,在swift 3中,新添了一个
fileprivate来显式的申明,这些成分的拜会权限为文件内私有千古的private对应未来的fileprivate。未来的private则是实在的私家,离开了那么些类照旧结构体的功用域外面就不能访问

提议读2次swift
blog
来理解OC与swift分歧以及swift版本变动细节

参考文献

Literals in Playgrounds

Xcode7.1发轫扶助字面量,首要用以颜色、图片、文件

本文首要商量Swift 三中的一些坑和行使进程中的一些小技术,排行无理由~~

Swift Value Types in Objective-C

Any可以具有其它的结构体、枚举、元组只怕其余的品类,OC的id在swift3等价于any,在swift第22中学须要手动封箱可能转入类,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()))

亟待注意的是swift三中对此周围的构造体类型将会桥接作为透明对象而不是cocoa对象,Int、UInt、Double、Bool会桥接为NSNumber,Int八,UInt1陆则单纯桥接为透明对象。假诺碰着了unrecognized selector sent to _SwiftValue主题素材,它意味着OC尝试唤醒叁个艺术在swift
值类型上,此时大家供给手动管理

swift Any持有任1类型包含Optional,即使OC api必要是nonull
id,Optional在未解包的事态下也得以用作参数传递,会产生runtime
error而不是编写翻译错误。swift三.0.壹+Xoce捌.壹消除了上述难题,为了制止包容难点,不要借助于透明对象因为前景的swift恐怕会桥接到固定类型

相较于Swift 二.贰 , 斯维夫特 3做了一点都不小的改观,慢慢脱离OC的影子。
语法上不少对象去掉了NS开端,去掉了繁琐的命名。如 UIColor.redColor() 改为
UIColor.red , 形成了质量,还有方法的率先个参数若是不钦命
_调用的时候也要写参数名等等…

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然后进行直接调用。着绝对于间接调用的快慢自然是慢的。

不再有CGRectMake,CGSizeMake等常用函数了

UIView(frame: CGRectMake(0, 0, 48, 48))
被改为
UIView(frame: CGRect(x: 0, y: 0, width: 48, height: 48))

// 'CGRectMake' is unavailable in Swift
// let frame = CGRect(0, 20, view.bounds.width, 130)        
// Swift 3.0 不再有CGRectMake,CGSizeMake等常用函数了        
 let frame = CGRect(x: 0, y: 20, width: view.bounds.width, height: 130)

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的磋商

AnyObject 、Any

事先任何项目为主只用 AnyObject
代表大多实例,基本也不和Any有哪些交集。因为斯维夫特 贰 对准Int、String
等结构体进行了转移,编写翻译器会自行桥接为NSNumber和NSString那种对象类型
,在swift三中AnyObject无法代表结构体了 。而 Any 能够象征 struct 、 class
、 func 等大概拥有类型。

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
    // ...
}

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>

需求小心的而是swift贰不再提供隐式调换,因此NS桥接的须求您显得调换

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
}

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

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)

Interactive Playgrounds

至于那里可以去看本身的简文playground准确接纳姿势

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
    }
}

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"]
}

Working with JSON in Swift

JSONSerialization Foundation framework

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
    }
}

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
    }
}

Strings in Swift 2

有关那里能够去看作者的简文你实在懂swift
string吗?

Nullability and Objective-C

骨子里对应的便是可选值

  • !表示非空
  • ?可空

Use Whole Module Optimization to infer final on internal declarations.

internal暗中认可的访问调节权限注解仅可以在模块可知。swift编写翻译文件是模块独立的,不可能分明internal申明在不一致的文书是还是不是被重写了。可是1旦整个模块的优化是开启的,全体的模块同时编写翻译、能够允许编写翻译器将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)
}

The AnyHashable Type

Any类型能够有所其余项目,但是Dictionary、Set供给Hasble,AnyHashble是swift三建议的hashable的超类,任何二个可hash的门类都落到实处了Anyhashble协议,举例String、Int

相关文章