Swift4.2新特性 & XCode 10更新


swift語法更新

SE-0079 允許self在閉包中使用可選綁定

// swift3
guard let `self` = self else {return}

// swift4.2
guard let self = self else {return}

使用上面代碼分別在swift3、swift4.2的閉包中將弱引用的self轉(zhuǎn)為強引用。但是Apple的Chris Lattner表示swift3的寫法是“一個編譯器錯誤”。

SE-0197添加removeAll(where:)方法到標(biāo)準(zhǔn)庫,用于刪除集合中滿足條件的元素

//swift 3
var nums = [1,2,3,4,5]
// 刪除奇數(shù)
nums = nums.filter { !isOdd($0) }

//swift 4.2
nums.removeAll(where: isOdd)

filter方法完成此操作存在性能問題 1.重新分配了內(nèi)存,2.需完整拷貝原數(shù)組

SE-0199添加.toggle()方法到BOOL值,讓原值反轉(zhuǎn)

//swift 3
myVar.prop1.prop2.enabled = !myVar.prop1.prop2.enabled

//swift 4.2
myVar.prop1.prop2.enabled.toggle()

SE-0202隨機數(shù)生成API

// 生成隨機數(shù)
Int.random(in: 1...1000)
UInt8.random(in: .min ... .max)
Double.random(in: 0..<1)

// 隨機從數(shù)組中取值
let emotions = "??????????????????"
let randomEmotion = emotions.randomElement()! //可能是其中一個

// 數(shù)組亂序
let numbers = 1...10
let shuffled = numbers.shuffled()//1-10的亂序數(shù)組

SE-0204添加last(where:)lastIndex(where:)獲取集合中最后滿足條件的元素和位置

// swift 3
let a = [20, 30, 10, 40, 20, 30, 10, 40, 20]
a.first(where: { $0 > 25 })         // 30
a.index(where: { $0 > 25 })         // 1
a.index(of: 10)                     // 2
// 需要獲取最后的需要將集合倒序
(a.reversed().index(where: { $0 > 25 })?.base).map({ a.index(before: $0) })
// swift 4.2
a.last(where: { $0 > 25 })          // 40
a.lastIndex(where: { $0 > 25 })     // 7
a.lastIndex(of: 10)                 // 6

SE-0206Hashable重新設(shè)計

// swift 3
extension Point: Equatable{
    func ==(lhs: Testhash, rhs: Testhash) -> Bool {
        return lhs.hashValue == rhs.hashValue
    }
}
extension Point: Equatable {
    var hashValue: Int {
        get {
            return self.x + self.y * self.x
        }
    }
}

// swift 4.2
extension Point: Equatable {
    static func ==(lhs: Point, rhs: Point) -> Bool {
        // Ignore distanceFromOrigin for determining equality
        return lhs.x == rhs.x && lhs.y == rhs.y
    }
}
extension Point: Hashable {
    func hash(into hasher: inout Hasher) {
        // Ignore distanceFromOrigin for hashing
        hasher.combine(x)
        hasher.combine(y)
    }
}

SE-0207集合新增.allSatisfy方法,判斷是否所有元素都滿足閉包內(nèi)的條件

// swift 3
//判斷所有數(shù)是否都是奇數(shù)
!nums.contains { !isOdd($0) }
//swift 4.2
nums.allSatisfy(isOdd)

SE-0143條件一致性,現(xiàn)在可以在擴展(extension)中合成協(xié)議一致性,而不僅僅是在類型定義上(擴展必須仍然位于與類型定義相同的文件中),并且允許自動合成Equatable, Hashable, Encodable, 和 Decodable.


func isEncodable(_ value: Any) -> Bool {
    return value is Encodable
}
let encodableArray = [1, 2, 3]

//Swift 4.1
isEncodable(encodableArray) // false

//Swift 4.2
isEncodable(encodableArray) // true
struct NonEncodable {}
let nonEncodableArray = [NonEncodable(), NonEncodable()]
isEncodable(nonEncodableArray)// false 在不滿足條件一致性條件時,動態(tài)查驗不成功。

enum Either<Left, Right> {
    case left(Left)
    case right(Right)
}

// 擴展后無需寫具體實現(xiàn),編譯器自動合成
extension Either: Equatable where Left: Equatable, Right: Equatable {}
extension Either: Hashable where Left: Hashable, Right: Hashable {}

Either<Int, String>.left(42) == Either<Int, String>.left(42)

SE-0212新增編譯器版本指令

// swift 3
#if swift(>=4.1) || (swift(>=3.3) && !swift(>=4.0))
// Code targeting the Swift 4.1 compiler and above.
#endif

#if swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))
// Code targeting the Swift 4.2 compiler and above.
#endif

#if swift(>=5.0) || (swift(>=4.1.50) && !swift(>=4.2)) || (swift(>=3.5) && !swift(>=4.0))
// Code targeting the Swift 5.0 compiler and above.
#endif

//swift4
#if swift(>=4.1) || (swift(>=3.3) && !swift(>=4.0))
// Code targeting the Swift 4.1 compiler and above.
// 低版本編譯器兼容代碼.
#endif

#if compiler(>=4.2)
// Code targeting the Swift 4.2 compiler and above.
#endif

#if compiler(>=5.0)
// Code targeting the Swift 5.0 compiler and above.
#endif

SE-0210添加MemoryLayout<T>.offset(of:)方法,返回一個指針地址偏移后的T類型的值

// C語言
// Layout of one of our vertex entries
struct MyVertex {
  float position[4];
  float normal[4];
  uint16_t texcoord[2];
};

enum MyVertexAttribute { Position, Normal, TexCoord };

glVertexAttribPointer(Position, 4, GL_FLOAT, GL_FALSE,
                      sizeof(MyVertex), (void*)offsetof(MyVertex, position));
glVertexAttribPointer(Normal, 4, GL_FLOAT, GL_FALSE,
                      sizeof(MyVertex), (void*)offsetof(MyVertex, normal));
glVertexAttribPointer(TexCoord, 2, GL_UNSIGNED_BYTE, GL_TRUE,
                      sizeof(MyVertex), (void*)offsetof(MyVertex, texcoord));
                      
//swift 4.2 
struct Point {
  var x, y: Double
}

struct Size {
  var w, h: Double

  var area: Double { return w*h }
}

struct Rect {
  var origin: Point
  var size: Size
}

MemoryLayout<Rect>.offset(of: \.origin.x) // => 0
MemoryLayout<Rect>.offset(of: \.origin.y) // => 8
MemoryLayout<Rect>.offset(of: \.size.w) // => 16
MemoryLayout<Rect>.offset(of: \.size.h) // => 24
MemoryLayout<Rect>.offset(of: \.size.area) // => nil

SE-0205只讀屬性withUnsafePointer(to:_:)withUnsafeBytes(of:_:) 頂層方法擴展

SE-0196編譯器指令#warning#error

// swift4.2
 #warning("TODO: missing implementation")//編譯器警告
 #error("This playground requires UIKit or AppKit")//編譯失敗報錯

SE-0195動態(tài)成員查找,通過@dynamicMemberLookup聲明屬性 ,以獲取 Python等語言的支持

// Python
class Dog:
   def __init__(self, name):
       self.name = name
       self.tricks = []    # creates a new empty list for each dog
   def add_trick(self, trick):
       self.tricks.append(trick)
       return self
----------------------------------------       
 //swift 4.2
 // import DogModule
 // import DogModule.Dog as Dog    // an alternate
 let Dog = Python.import("DogModule.Dog")
 let dog = Dog("Brianna")
 dog.add_trick("Roll over")
 let cuteDog = Dog("Kaylee").add_trick("snore")

SE-0194遍歷普通枚舉值

enum Terrain: CaseIterable {
    case water
    case forest
    case desert
    case road
}

Terrain.allCases
Terrain.allCases.count

使用CaseIterable后,枚舉可以通過.allCases獲取所有枚舉值的數(shù)組

SE-0193模塊間調(diào)用, 用@inlinable and @usableFromInline聲明公共接口

// Inside CollectionAlgorithms module:
extension Sequence where Element: Equatable {
    /// Returns `true` iff all elements in the sequence are equal.
    @inlinable
    public func allEqual() -> Bool {
        var iterator = makeIterator()
        guard let first = iterator.next() else {
            return true
        }
        while let next = iterator.next() {
            if first != next {
                return false
            }
        }
        return true
    }
}

[1,1,1,1,1].allEqual()
Array(repeating: 42, count: 1000).allEqual()
[1,1,2,1,1].allEqual()

SE-0054廢除隱式可選類型

let x: Int! = 5   //x:Int!
let y = x         //y:Int?
let z = x + 0     //z:Int

X在使用時被強制解包為Int類型,聲明的類型表示可選類型,并且告知編譯器可以強制解包[Int!]<T!>等類型將不再可用,類似的自動類型推導(dǎo)也將提示修改為指定類型

XCode 10更新


  1. 多行編輯:control + shift +鼠標(biāo)單擊

多行編輯在Mac OS10.14中可以在眾多編輯器中使用如Sublime Text3中可以用command+鼠標(biāo)單擊 點擊多行編輯(支持多行分別復(fù)制粘貼)

linesedit.gif

  1. 為快速查看彈出窗口添加了導(dǎo)出選項,用于數(shù)據(jù)類型,例如NSData


    屏幕快照 2018-09-19 上午11.04.52.png
  1. 現(xiàn)在,新創(chuàng)建的schemes默認(rèn)由Xcode項目的所有用戶共享。要創(chuàng)建個人方案,請取消選中Manage Schemes表中的Shared復(fù)選框

  2. 打開Library時按住Option鍵將使其在手動關(guān)閉之前保持可見,而不是在每次使用后自動關(guān)閉。(使用command+shift+M/L打開媒體庫或UI組件庫,拖去UI組件時按住Option殼使彈出視圖不消失)

    屏幕快照 2018-09-19 上午11.24.25.png

  3. xcode的10增加了對C ++ 17個頭部的支持<any>,<optional>和<variant>。(39271859)

  4. 命名顏色現(xiàn)在可以象征性地引用系統(tǒng)顏色。(39196638)

  5. libstdc ++已在xcode10棄用,C ++項目現(xiàn)在必須遷移到libc++,開發(fā)人員還應(yīng)審核項目依賴項,以刪除對libstdc++的引用

  6. Libgcc已經(jīng)過時了。Xcode 10無法再構(gòu)建具有macOS 10.4和10.5部署目標(biāo)的應(yīng)用程序。(42818150,38035243)

  7. 已刪除對Subversion(SVN)的支持,目前只支持Git

  8. Xcode 10是最后一個支持Swift 3的版本。通過打開項目并選擇Edit> Convert> To Current Swift Syntax ...將項目從Swift 3代碼遷移到Swift 4.2語法...(43101816)

  9. macOS 10.14 SDK不再包含對編譯32位應(yīng)用程序的支持。如果開發(fā)人員需要為i386編譯,則需要Xcode 9.4或更早版本。

  10. 調(diào)試工具增強
    更多信息請閱讀參考文檔中的《Xcode 10 Release Notes》

XCode10已知BUG

  1. 打開存儲在iCloud Drive中的Xcode項目和工作空間,或更改存儲在iCloud Drive中的打開的工作空間或項目的源控制分支,可能會導(dǎo)致Xcode掛起。
  2. 運行iOS 12的設(shè)備可能無法從Xcode的設(shè)備窗口獲取請求的屏幕截圖。(42873539)
    解決方法:在設(shè)備上截取屏幕截圖。
  3. 使用以前版本的Xcode構(gòu)建的Xcode 10運行WatchKit應(yīng)用程序可能會出現(xiàn)安裝錯誤“WatchKit應(yīng)用程序具有無效的存根可執(zhí)行文件”。(40567857)
    解決方法:清理構(gòu)建文件夾并再次運行應(yīng)用程序。
  4. 如果Xcode尚未連接完成任何開發(fā)設(shè)備,則Instruments可能無法啟動。(43066159)
    解決方法:等待Xcode的設(shè)備設(shè)置階段完成,然后打開Instruments。
  5. Instruments可能無法在iOS模擬器中配置庫或框架單元測試
  6. 在playground中切換到非默認(rèn)工具鏈可能會導(dǎo)致Xcode崩潰。(43659135)
    解決方法:切換回默認(rèn)工具鏈,然后打開playground。
  7. 模擬設(shè)備中的macOS粘貼板和粘貼板之間的同步有時會失敗。(36036706,38052949,41916640)
  8. 操作系統(tǒng)可能需要幾分鐘才能在模擬器中首次啟動。(40535421)
  9. Xcode不支持ed25519加密的SSH密鑰對。(40912136)
    解決方法:使用使用不同加密形式的SSH密鑰對。

參考文檔

1.whats-new-in-swift-4-2
2.swift change Log
3.swift-4-2-released
4.Xcode 10 Release Notes

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。