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:)
方法到標準庫,用于刪除集合中滿足條件的元素
//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更新
- 多行編輯:
control
+shift
+鼠標單擊
多行編輯在Mac OS10.14中可以在眾多編輯器中使用如Sublime Text3中可以用
command
+鼠標單擊 點擊多行編輯(支持多行分別復(fù)制粘貼)
-
為快速查看彈出窗口添加了導(dǎo)出選項地啰,用于數(shù)據(jù)類型愁拭,例如NSData
現(xiàn)在,新創(chuàng)建的
schemes
默認由Xcode項目的所有用戶共享亏吝。要創(chuàng)建個人方案岭埠,請取消選中Manage Schemes
表中的Shared
復(fù)選框-
打開Library時按住Option鍵將使其在手動關(guān)閉之前保持可見,而不是在每次使用后自動關(guān)閉蔚鸥。(使用
command
+shift
+M
/L
打開媒體庫或UI組件庫惜论,拖去UI組件時按住Option殼使彈出視圖不消失)
xcode的10增加了對C ++ 17個頭部的支持<any>,<optional>和<variant>止喷。(39271859)
命名顏色現(xiàn)在可以象征性地引用系統(tǒng)顏色馆类。(39196638)
libstdc ++已在xcode10棄用,C ++項目現(xiàn)在必須遷移到libc++启盛,開發(fā)人員還應(yīng)審核項目依賴項,以刪除對libstdc++的引用
Libgcc已經(jīng)過時了技羔。Xcode 10無法再構(gòu)建具有macOS 10.4和10.5部署目標的應(yīng)用程序僵闯。(42818150,38035243)
已刪除對Subversion(SVN)的支持,目前只支持Git
Xcode 10是最后一個支持Swift 3的版本。通過打開項目并選擇Edit> Convert> To Current Swift Syntax ...將項目從Swift 3代碼遷移到Swift 4.2語法...(43101816)
macOS 10.14 SDK不再包含對編譯32位應(yīng)用程序的支持藤滥。如果開發(fā)人員需要為i386編譯鳖粟,則需要Xcode 9.4或更早版本。
調(diào)試工具增強
更多信息請閱讀參考文檔中的《Xcode 10 Release Notes》
XCode10已知BUG
- 打開存儲在iCloud Drive中的Xcode項目和工作空間拙绊,或更改存儲在iCloud Drive中的打開的工作空間或項目的源控制分支向图,可能會導(dǎo)致Xcode掛起。
- 運行iOS 12的設(shè)備可能無法從Xcode的設(shè)備窗口獲取請求的屏幕截圖标沪。(42873539)
解決方法:在設(shè)備上截取屏幕截圖榄攀。 - 使用以前版本的Xcode構(gòu)建的Xcode 10運行WatchKit應(yīng)用程序可能會出現(xiàn)安裝錯誤“WatchKit應(yīng)用程序具有無效的存根可執(zhí)行文件”。(40567857)
解決方法:清理構(gòu)建文件夾并再次運行應(yīng)用程序金句。 - 如果Xcode尚未連接完成任何開發(fā)設(shè)備檩赢,則Instruments可能無法啟動。(43066159)
解決方法:等待Xcode的設(shè)備設(shè)置階段完成违寞,然后打開Instruments贞瞒。 - Instruments可能無法在iOS模擬器中配置庫或框架單元測試
- 在playground中切換到非默認工具鏈可能會導(dǎo)致Xcode崩潰偶房。(43659135)
解決方法:切換回默認工具鏈,然后打開playground军浆。 - 模擬設(shè)備中的macOS粘貼板和粘貼板之間的同步有時會失敗棕洋。(36036706,38052949,41916640)
- 操作系統(tǒng)可能需要幾分鐘才能在模擬器中首次啟動。(40535421)
- 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