1、訪問控制
Swift 提供了5個不同的訪問級別:open > public > internal > fileprivate > private
open:允許在本模塊中訪問、繼承、重寫,允許其他模塊訪問、繼承、重寫(open 只能用在類、類成員上)。
public:允許在本模塊中訪問、繼承、重寫,只允許其他模塊訪問。
internal:只允許在本模塊中訪問、繼承、重寫,不允許其他模塊訪問。默認(rèn)權(quán)限。
fileprivate:只允許在定義的源碼文件中訪問。
private:只允許在定義實(shí)體的封閉聲明中訪問。
使用規(guī)則:
一個實(shí)體不可以被更低訪問級別的實(shí)體定義,比如:
變量\常量類型 ≥ 變量\常量
參數(shù)類型、返回值類型 ≥ 函數(shù)
父類 ≥ 子類
父協(xié)議 ≥ 子協(xié)議
原類型 ≥ typealias
原始值類型、關(guān)聯(lián)值類型 ≥ 枚舉類型
定義類型A時用到的其他類型 ≥ 類型A
元組:
元組類型的訪問級別是所有成員類型最低的那個。
泛型類型:
泛型類型的訪問級別是類型的訪問級別以及所有泛型類型參數(shù)的訪問級別中最低的那個。
成員、嵌套類型:
類型的訪問級別會影響成員(屬性、方法、初始化器、下標(biāo))、嵌套類型的默認(rèn)訪問級別。若類型為 private 或 fileprivate,那么成員\嵌套類型默認(rèn)也是 private 或 fileprivate;若類型為 internal 或 public,那么成員\嵌套類型默認(rèn)是 internal。
成員的重寫:
1、子類重寫成員的訪問級別必須 ≥ 子類的訪問級別/父類被重寫成員的訪問級別。
2、父類的成員不能被成員作用域外定義的子類重寫。
全局作用域:
直接在全局作用域下定義的 private 等價于 fileprivate。
getter、setter:
getter、setter 默認(rèn)自動接收它們所屬環(huán)境的訪問級別。也可以給 setter 單獨(dú)設(shè)置一個比 getter 更低的訪問級別,用以限制寫的權(quán)限。
初始化器:
1、如果一個 public 類想在另一個模塊調(diào)用編譯生成的默認(rèn)無參初始化器,必須顯式提供 public 的無參初始化器。因?yàn)?public 類的默認(rèn)初始化器是 internal 級別。
2、required 初始化器 ≥ 它的默認(rèn)訪問級別。
3、如果結(jié)構(gòu)體有 private\fileprivate 的存儲實(shí)例屬性,那么它的成員初始化器也是 private\fileprivate,否則默認(rèn)就是 internal。
枚舉類型的 case:
1、不能給 enum 的每個 case 單獨(dú)設(shè)置訪問級別
2、每個 case 自動接收 enum 的訪問級別,enum 為 public 時 case 也是 public。
協(xié)議:
1、協(xié)議中定義的要求自動接收協(xié)議的訪問級別,不能單獨(dú)設(shè)置訪問級別。public 協(xié)議定義的要求也是 public。
2、協(xié)議實(shí)現(xiàn)的訪問級別必須 ≥ 類型的訪問級別 / 協(xié)議的訪問級別。
擴(kuò)展:
1、如果有顯式設(shè)置擴(kuò)展的訪問級別,擴(kuò)展添加的成員自動接收擴(kuò)展的訪問級別。如果沒有顯式設(shè)置擴(kuò)展的訪問級別,擴(kuò)展添加的成員的默認(rèn)訪問級別,跟直接在類型中定義的成員一樣。
2、可以單獨(dú)給擴(kuò)展添加的成員設(shè)置訪問級別。
3、不能給用于遵守協(xié)議的擴(kuò)展顯式設(shè)置擴(kuò)展的訪問級別。
4、在同一文件中的擴(kuò)展,可以寫成類似多個部分的類型聲明。在原本的聲明中聲明一個私有成員,可以在同一文件的擴(kuò)展中訪問它。在擴(kuò)展中聲明一個私有成員,可以在同一文件的其他擴(kuò)展中、原本聲明中訪問它。
2、內(nèi)存管理
跟 OC 一樣,Swift 也是采取基于引用計數(shù)的 ARC 內(nèi)存管理方案(針對堆空間)。
Swift 的 ARC 中有3種引用
1、強(qiáng)引用(strong reference):默認(rèn)情況下引用都是強(qiáng)引用。
2、弱引用(weak reference):通過 weak 定義弱引用。必須是可選類型的 var,因?yàn)閷?shí)例銷毀后,ARC 會自動將弱引用設(shè)置為 nil。ARC 自動給弱引用設(shè)置 nil 時,不會觸發(fā)屬性觀察器。
3、無主引用(unowned reference):通過 unowned 定義無主引用。它不會產(chǎn)生強(qiáng)引用,實(shí)例銷毀后仍然存儲著實(shí)例的內(nèi)存地址(類似于OC中的 unsafe_unretained)。試圖在實(shí)例銷毀后訪問無主引用,會產(chǎn)生運(yùn)行時錯誤(野指針)。
weak、unowned 的使用條件:只能用在類實(shí)例上面。
循環(huán)引用:
weak、unowned 都能解決循環(huán)引用的問題,unowned 要比 weak 少一些性能消耗。在生命周期中可能會變?yōu)?nil 的使用 weak。初始化賦值后再也不會變?yōu)?nil 的使用 unowned。
閉包的循環(huán)引用:
1、閉包表達(dá)式默認(rèn)會對用到的外層對象產(chǎn)生強(qiáng)引用(對外層對象進(jìn)行了 retain 操作)。在閉包表達(dá)式的捕獲列表聲明 weak 或 unowned 引用,解決循環(huán)引用問題。
2、如果想在定義閉包屬性的同時引用 self,這個閉包必須是 lazy 的(因?yàn)樵趯?shí)例初始化完畢之后才能引用 self)。
3、如果 lazy 屬性是閉包調(diào)用的結(jié)果,那么不用考慮循環(huán)引用的問題(因?yàn)殚]包調(diào)用后,閉包的生命周期就結(jié)束了)。
@escaping:
1、非逃逸閉包、逃逸閉包,一般都是當(dāng)做參數(shù)傳遞給函數(shù)。
非逃逸閉包:閉包調(diào)用發(fā)生在函數(shù)結(jié)束前,閉包調(diào)用在函數(shù)作用域內(nèi)。
逃逸閉包:閉包有可能在函數(shù)結(jié)束后調(diào)用,閉包調(diào)用逃離了函數(shù)的作用域,需要通過 @escaping 聲明。
2、逃逸閉包不可以捕獲 inout 參數(shù)。
內(nèi)存訪問沖突:
內(nèi)存訪問沖突會在兩個訪問滿足下列條件時發(fā)生:
1、至少一個是寫入操作。
2、它們訪問的是同一塊內(nèi)存。
3、它們的訪問時間重疊(比如在同一個函數(shù)內(nèi))。
// 不存在內(nèi)存訪問沖突
func plus(_ num: inout Int) -> Int { num + 1 }
var number = 1
number = plus(&number)
// 存在內(nèi)存訪問沖突
// Simultaneous accesses to 0x0, but modification requires exclusive access
var step = 1
func increment(_ num: inout Int) { num += step }
increment(&step)
// 解決內(nèi)存訪問沖突
var copyOfStep = step
increment(©OfStep)
step = copyOfStep
func balance(_ x: inout Int, _ y: inout Int) {
let sum = x + y
x = sum / 2
y = sum - x
}
var num1 = 42
var num2 = 30
balance(&num1, &num2) // OK
balance(&num1, &num1) // Error
struct Player {
var name: String
var health: Int
var energy: Int
mutating func shareHealth(with teammate: inout Player) {
balance(&teammate.health, &health)
}
}
var oscar = Player(name: "Oscar", health: 10, energy: 10)
var maria = Player(name: "Maria", health: 5, energy: 10)
oscar.shareHealth(with: &maria) // OK
oscar.shareHealth(with: &oscar) // Error
var tulpe = (health: 10, energy: 20)
// Error
balance(&tulpe.health, &tulpe.energy)
var holly = Player(name: "Holly", health: 10, energy: 10)
// Error
balance(&holly.health, &holly.energy)
如果下面的條件可以滿足,說明重疊訪問結(jié)構(gòu)體的屬性是安全的:
1、只訪問實(shí)例存儲屬性,不是計算屬性或者類屬性。
2、結(jié)構(gòu)體是局部變量而非全局變量。
3、結(jié)構(gòu)體要么沒有被閉包捕獲要么只被非逃逸閉包捕獲。
// Ok
func test() {
var tulpe = (health: 10, energy: 20)
balance(&tulpe.health, &tulpe.energy)
var holly = Player(name: "Holly", health: 10, energy: 10)
balance(&holly.health, &holly.energy)
}
test()
指針
1、Swift 中也有專門的指針類型,這些都被定性為 Unsafe(不安全的),常見的有以下4種類型:
UnsafePointer<Pointee> 類似于 const Pointee *。
UnsafeMutablePointer<Pointee> 類似于 Pointee *。
UnsafeRawPointer 類似于 const void *。
UnsafeMutableRawPointer 類似于 void *。
var age = 10
func test1(_ ptr: UnsafeMutablePointer<Int>) {
ptr.pointee += 10
}
func test2(_ ptr: UnsafePointer<Int>) {
print(ptr.pointee)
}
test1(&age)
test2(&age) // 20
print(age) // 20
var age = 10
func test3(_ ptr: UnsafeMutableRawPointer) {
ptr.storeBytes(of: 20, as: Int.self)
}
func test4(_ ptr: UnsafeRawPointer) {
print(ptr.load(as: Int.self))
}
test3(&age)
test4(&age) // 20
print(age) // 20
2、應(yīng)用
var arr = NSArray(objects: 11, 22, 33, 44)
arr.enumerateObjects { (obj, idx, stop) in
print(idx, obj)
if idx == 2 { // 下標(biāo)為2就停止遍歷
stop.pointee = true
}
}
var arr = NSArray(objects: 11, 22, 33, 44)
for (idx, obj) in arr.enumerated() {
print(idx, obj)
if idx == 2 {
break
}
}
3、獲得指向某個變量的指針
var age = 11
var ptr1 = withUnsafeMutablePointer(to: &age) { $0 }
var ptr2 = withUnsafePointer(to: &age) { $0 }
ptr1.pointee = 22
print(ptr2.pointee) // 22
print(age) // 22
var ptr3 = withUnsafeMutablePointer(to: &age) { UnsafeMutableRawPointer($0) }
var ptr4 = withUnsafePointer(to: &age) { UnsafeRawPointer($0) }
ptr3.storeBytes(of: 33, as: Int.self)
print(ptr4.load(as: Int.self)) // 33
print(age) // 33
4、獲得指向堆空間實(shí)例的指針
class Person {}
var person = Person()
var ptr = withUnsafePointer(to: &person) { UnsafeRawPointer($0) }
var heapPtr = UnsafeRawPointer(bitPattern: ptr.load(as: UInt.self))
print(heapPtr!)
5、創(chuàng)建指針
var ptr = UnsafeRawPointer(bitPattern: 0x100001234)
// 創(chuàng)建
var ptr = malloc(16)
// 存
ptr?.storeBytes(of: 11, as: Int.self)
ptr?.storeBytes(of: 22, toByteOffset: 8, as: Int.self)
// 取
print((ptr?.load(as: Int.self))!) // 11
print((ptr?.load(fromByteOffset: 8, as: Int.self))!) // 22
// 銷毀
free(ptr)
var ptr = UnsafeMutableRawPointer.allocate(byteCount: 16, alignment: 1)
ptr.storeBytes(of: 11, as: Int.self)
ptr.advanced(by: 8).storeBytes(of: 22, as: Int.self)
print(ptr.load(as: Int.self)) // 11
print(ptr.advanced(by: 8).load(as: Int.self)) // 22
ptr.deallocate()
var ptr = UnsafeRawPointer(bitPattern: 0x100001234)
var ptr = UnsafeMutablePointer<Int>.allocate(capacity: 3)
ptr.initialize(to: 11)
ptr.successor().initialize(to: 22)
ptr.successor().successor().initialize(to: 33)
print(ptr.pointee) // 11
print((ptr + 1).pointee) // 22
print((ptr + 2).pointee) // 33
print(ptr[0]) // 11
print(ptr[1]) // 22
print(ptr[2]) // 33
ptr.deinitialize(count: 3)
ptr.deallocate()
class Person {
var age: Int
var name: String
init(age: Int, name: String) {
self.age = age
self.name = name
}
deinit { print(name, "deinit") }
}
var ptr = UnsafeMutablePointer<Person>.allocate(capacity: 3)
ptr.initialize(to: Person(age: 10, name: "Jack"))
(ptr + 1).initialize(to: Person(age: 11, name: "Rose"))
(ptr + 2).initialize(to: Person(age: 12, name: "Kate"))
// Jack deinit
// Rose deinit
// Kate deinit
ptr.deinitialize(count: 3)
ptr.deallocate()
6、指針轉(zhuǎn)換
var ptr = UnsafeMutableRawPointer.allocate(byteCount: 16, alignment: 1)
ptr.assumingMemoryBound(to: Int.self).pointee = 11
(ptr + 8).assumingMemoryBound(to: Double.self).pointee = 22.0
print(unsafeBitCast(ptr, to: UnsafePointer<Int>.self).pointee) // 11
print(unsafeBitCast(ptr + 8, to: UnsafePointer<Double>.self).pointee) // 22.0
ptr.deallocate()
unsafeBitCast 是忽略數(shù)據(jù)類型的強(qiáng)制轉(zhuǎn)換,不會因?yàn)閿?shù)據(jù)類型的變化而改變原來的內(nèi)存數(shù)據(jù)。
class Person {}
var person = Person()
var ptr = unsafeBitCast(person, to: UnsafeRawPointer.self)
print(ptr)
3、字面量
常見字面量(Literal)的默認(rèn)類型:
public typealias IntegerLiteralType = Int
public typealias FloatLiteralType = Double
public typealias BooleanLiteralType = Bool
public typealias StringLiteralType = String
// 可以通過typealias修改字面量的默認(rèn)類型
typealias FloatLiteralType = Float
typealias IntegerLiteralType = UInt8
var age = 10 // UInt8
var height = 1.68 // Float
Swift 自帶的絕大部分類型,都支持直接通過字面量進(jìn)行初始化:Bool、Int、Float、Double、String、Array、Dictionary、Set、Optional 等。Swift 自帶類型之所以能夠通過字面量初始化,是因?yàn)樗鼈冏袷亓藢?yīng)的協(xié)議。
Bool : ExpressibleByBooleanLiteral
Int : ExpressibleByIntegerLiteral
Float、Double : ExpressibleByIntegerLiteral、ExpressibleByFloatLiteral
Dictionary : ExpressibleByDictionaryLiteral
String : ExpressibleByStringLiteral
Array、Set : ExpressibleByArrayLiteral
Optional : ExpressibleByNilLiteral
字面量協(xié)議應(yīng)用
extension Int : ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) { self = value ? 1 : 0 }
}
var num: Int = true
print(num) // 1
class Student : ExpressibleByIntegerLiteral, ExpressibleByFloatLiteral, ExpressibleByStringLiteral, CustomStringConvertible {
var name: String = ""
var score: Double = 0
required init(floatLiteral value: Double) { self.score = value }
required init(integerLiteral value: Int) { self.score = Double(value) }
required init(stringLiteral value: String) { self.name = value }
required init(unicodeScalarLiteral value: String) { self.name = value }
required init(extendedGraphemeClusterLiteral value: String) { self.name = value }
var description: String { "name=\(name),score=\(score)" }
}
var stu: Student = 90
print(stu) // name=,score=90.0
stu = 98.5
print(stu) // name=,score=98.5
stu = "Jack"
print(stu) // name=Jack,score=0.0
struct Point {
var x = 0.0, y = 0.0
}
extension Point : ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral {
init(arrayLiteral elements: Double...) {
guard elements.count > 0 else { return }
self.x = elements[0]
guard elements.count > 1 else { return }
self.y = elements[1]
}
init(dictionaryLiteral elements: (String, Double)...) {
for (k, v) in elements {
if k == "x" { self.x = v } else if k == "y" { self.y = v }
}
}
}
var p: Point = [10.5, 20.5]
print(p) // Point(x: 10.5, y: 20.5)
p = ["x" : 11, "y" : 22]
print(p) // Point(x: 11.0, y: 22.0)
4、模式匹配
模式是用于匹配的規(guī)則,比如 switch 的 case、捕捉錯誤的 catch、if\guard\while\for 語句的條件等。
Swift中的模式有:
通配符模式(Wildcard Pattern)
標(biāo)識符模式(Identifier Pattern)
值綁定模式(Value-Binding Pattern)
元組模式(Tuple Pattern)
枚舉 Case 模式(Enumeration Case Pattern)
可選模式(Optional Pattern)
類型轉(zhuǎn)換模式(Type-Casting Pattern)
表達(dá)式模式(Expression Pattern)
通配符模式(Wildcard Pattern):
_ 匹配任何值
_? 匹配非 nil 值
enum Life {
case human(name: String, age: Int?)
case animal(name: String, age: Int?)
}
func check(_ life: Life) {
switch life {
case .human(let name, _):
print("human", name)
case .animal(let name, _?):
print("animal", name)
default:
print("other")
}
}
check(.human(name: "Rose", age: 20)) // human Rose
check(.human(name: "Jack", age: nil)) // human Jack
check(.animal(name: "Dog", age: 5)) // animal Dog
check(.animal(name: "Cat", age: nil)) // other
標(biāo)識符模式(Identifier Pattern)
給對應(yīng)的變量、常量名賦值
var age = 10
let name = "jack"
值綁定模式(Value-Binding Pattern)
let point = (3, 2)
switch point {
case let (x, y):
print("The point is at (\(x), \(y)).")
}
元組模式(Tuple Pattern)
let points = [(0, 0), (1, 0), (2, 0)]
for (x, _) in points {
print(x)
}
let name: String? = "jack"
let age = 18
let info: Any = [1, 2]
switch (name, age, info) {
case (_?, _ , _ as String):
print("case")
default:
print("default")
} // default
var scores = ["jack" : 98, "rose" : 100, "kate" : 86]
for (name, score) in scores {
print(name, score)
}
枚舉 Case 模式(Enumeration Case Pattern)
if case 語句等價于只有1個 case 的 switch 語句
let age = 2
// 原來的寫法
if age >= 0 && age <= 9 {
print("[0, 9]")
}
// 枚舉Case模式
if case 0...9 = age {
print("[0, 9]")
}
guard case 0...9 = age else { return }
print("[0, 9]")
switch age {
case 0...9: print("[0, 9]")
default: break
}
let ages: [Int?] = [2, 3, nil, 5]
for case nil in ages {
print("有nil值")
break
} // 有nil值
let points = [(1, 0), (2, 1), (3, 0)]
for case let (x, 0) in points {
print(x)
} // 1 3
可選模式(Optional Pattern)
let age: Int? = 42
if case .some(let x) = age { print(x) }
if case let x? = age { print(x) }
let ages: [Int?] = [nil, 2, 3, nil, 5]
for case let age? in ages {
print(age)
} // 2 3 5
let ages: [Int?] = [nil, 2, 3, nil, 5]
for item in ages {
if let age = item {
print(age)
}
} // 跟上面的for,效果是等價的
func check(_ num: Int?) {
switch num {
case 2?: print("2")
case 4?: print("4")
case 6?: print("6")
case _?: print("other")
case _: print("nil")
}
}
check(4) // 4
check(8) // other
check(nil) // nil
類型轉(zhuǎn)換模式(Type-Casting Pattern)
let num: Any = 6
switch num {
case is Int:
// 編譯器依然認(rèn)為num是Any類型
print("is Int", num)
//case let n as Int:
// print("as Int", n + 1)
default:
break
}
class Animal { func eat() { print(type(of: self), "eat") } }
class Dog : Animal { func run() { print(type(of: self), "run") } }
class Cat : Animal { func jump() { print(type(of: self), "jump") } }
func check(_ animal: Animal) {
switch animal {
case let dog as Dog:
dog.eat()
dog.run()
case is Cat:
animal.eat()
default: break
}
}
// Dog eat
// Dog run
check(Dog())
// Cat eat
check(Cat())
表達(dá)式模式(Expression Pattern)
表達(dá)式模式用在 case 中
let point = (1, 2)
switch point {
case (0, 0):
print("(0, 0) is at the origin.")
case (-2...2, -2...2):
print("(\(point.0), \(point.1)) is near the origin.")
default:
print("The point is at (\(point.0), \(point.1)).")
} // (1, 2) is near the origin.
自定義表達(dá)式模式
可以通過重載運(yùn)算符,自定義表達(dá)式模式的匹配規(guī)則。
struct Student {
var score = 0, name = ""
static func ~= (pattern: Int, value: Student) -> Bool { value.score >= pattern }
static func ~= (pattern: ClosedRange<Int>, value: Student) -> Bool { pattern.contains(value.score) }
static func ~= (pattern: Range<Int>, value: Student) -> Bool { pattern.contains(value.score) }
}
var stu = Student(score: 75, name: "Jack")
switch stu {
case 100: print(">= 100")
case 90: print(">= 90")
case 80..<90: print("[80, 90)")
case 60...79: print("[60, 79]")
case 0: print(">= 0")
default: break
} // [60, 79]
if case 60 = stu {
print(">= 60")
} // >= 60
var info = (Student(score: 70, name: "Jack"), "及格")
switch info {
case let (60, text): print(text)
default: break
} // 及格
extension String {
static func ~= (pattern: (String) -> Bool, value: String) -> Bool {
pattern(value)
}
}
func hasPrefix(_ prefix: String) -> ((String) -> Bool) { { $0.hasPrefix(prefix) } }
func hasSuffix(_ suffix: String) -> ((String) -> Bool) { { $0.hasSuffix(suffix) } }
var str = "jack"
switch str {
case hasPrefix("j"), hasSuffix("k"):
print("以j開頭,以k結(jié)尾")
default: break
} // 以j開頭,以k結(jié)尾
func isEven(_ i: Int) -> Bool { i % 2 == 0 }
func isOdd(_ i: Int) -> Bool { i % 2 != 0 }
extension Int {
static func ~= (pattern: (Int) -> Bool, value: Int) -> Bool {
pattern(value)
}
}
var age = 9
switch age {
case isEven:
print("偶數(shù)")
case isOdd:
print("奇數(shù)")
default:
print("其他")
}
prefix operator ~>
prefix operator ~>=
prefix operator ~<
prefix operator ~<=
prefix func ~> (_ i: Int) -> ((Int) -> Bool) { { $0 > i } }
prefix func ~>= (_ i: Int) -> ((Int) -> Bool) { { $0 >= i } }
prefix func ~< (_ i: Int) -> ((Int) -> Bool) { { $0 < i } }
prefix func ~<= (_ i: Int) -> ((Int) -> Bool) { { $0 <= i } }
var age = 9
switch age {
case ~>=0:
print("1")
case ~>10:
print("2")
default: break
} // [0, 10]
where
可以使用 where 為模式匹配增加匹配條件
var data = (10, "Jack")
switch data {
case let (age, _) where age > 10:
print(data.1, "age>10")
case let (age, _) where age > 0:
print(data.1, "age>0")
default: break
}
var ages = [10, 20, 44, 23, 55]
for age in ages where age > 30 {
print(age)
} // 44 55
protocol Stackable { associatedtype Element }
protocol Container {
associatedtype Stack : Stackable where Stack.Element : Equatable
}
func equal<S1: Stackable, S2: Stackable>(_ s1: S1, _ s2: S2) -> Bool where S1.Element == S2.Element, S1.Element : Hashable {
return false
}
extension Container where Self.Stack.Element : Hashable { }
注:
方法也可以像函數(shù)那樣,賦值給一個 let 或者 var。
struct Person {
var age: Int
func run(_ v: Int) { print("func run", age, v) }
static func run(_ v: Int) { print("static func run", v) }
}
let fn1 = Person.run
fn1(10) // static func run 10
let fn2: (Int) -> () = Person.run
fn2(20) // static func run 20
let fn3: (Person) -> ((Int) -> ()) = Person.run
fn3(Person(age: 18))(30) // func run 18 30