- 協(xié)議可以用來定義方法、屬性夹纫、下標(biāo)的聲明咽瓷,協(xié)議可以被枚舉、結(jié)構(gòu)體捷凄、類遵守(多個(gè)協(xié)議之間用逗號(hào)隔開)
protocol Drawable {
func draw()
var x: Int { get set }
var y: Int { get }
subscript(index: Int) -> Int { get set }
}
protocol Test1 {}
protocol Test2 {}
protocol Test3 {}
class TestClass : Test1, Test2, Test3 {}
協(xié)議中定義方法時(shí)不能有默認(rèn)參數(shù)值
默認(rèn)情況下忱详,協(xié)議中定義的內(nèi)容必須全部都實(shí)現(xiàn)
也有辦法辦到只實(shí)現(xiàn)部分內(nèi)容,以后的課程會(huì)講到
protocol Drawable {
func draw()
var x: Int { get set }
var y: Int { get }
subscript(index: Int) -> Int { get set }
}
class Person : Drawable {
var x: Int = 0
let y: Int = 0
func draw() {
print("Person draw")
}
subscript(index: Int) -> Int {
set {}
get { index }
}
}
class Person : Drawable {
var x: Int {
get { 0 }
set {}
}
var y: Int { 0 }
func draw() { print("Person draw") }
subscript(index: Int) -> Int {
set {}
get { index }
}
}
- 協(xié)議中定義屬性時(shí)必須用 關(guān)鍵字
- 實(shí)現(xiàn)協(xié)議時(shí)的屬性權(quán)限要協(xié)議中定義的屬性權(quán)限
- 協(xié)議定義跺涤、匈睁,用存儲(chǔ)屬性或、計(jì)算屬性去實(shí)現(xiàn)
- 協(xié)議定義桶错,用任何屬性都可以實(shí)現(xiàn)
- 為了保證通用航唆,協(xié)議中必須用定義類型方法、類型屬性院刁、類型下標(biāo)
protocol Drawable {
static func draw()
}
class Person1 : Drawable {
class func draw() {
print("Person1 draw")
}
}
class Person2 : Drawable {
static func draw() {
print("Person2 draw")
}
}
- 只有將協(xié)議中的實(shí)例方法標(biāo)記為mutating
- 才允許結(jié)構(gòu)體糯钙、枚舉的具體實(shí)現(xiàn)修改自身內(nèi)存
- 類在實(shí)現(xiàn)方法時(shí)不用加mutating,枚舉、結(jié)構(gòu)體才需要加mutating
protocol Drawable {
mutating func draw()
}
class Size : Drawable {
var width: Int = 0
func draw() {
width = 10
}
}
struct Point : Drawable {
var x: Int = 0
mutating func draw() {
x = 10
}
}
- 協(xié)議中還可以定義初始化器init
- 非final類實(shí)現(xiàn)時(shí)必須加上
protocol Drawable {
init(x: Int, y: Int)
}
class Point : Drawable {
required init(x: Int, y: Int) {} }}
}
final class Size : Drawable {
init(x: Int, y: Int) {}
}
如果從協(xié)議實(shí)現(xiàn)的初始化器任岸,剛好是重寫了父類的指定初始化器
那么這個(gè)初始化必須同時(shí)加再榄、
protocol Livable {
init(age: Int)
}
class Person {
init(age: Int) {}
}
class Student : Person, Livable {
required override init(age: Int) {
super.init(age: age)
}
}
- 協(xié)議中定義的init?享潜、init!困鸥,可以用init、init?剑按、init!去實(shí)現(xiàn)
- 協(xié)議中定義的init疾就,可以用init、init!去實(shí)現(xiàn)
protocol Livable {
init()
init?(age: Int)
init!(no: Int)
}
class Person : Livable {
required init() {}
// required init!() {}
required init?(age: Int) {}
// required init!(age: Int) {}
// required init(age: Int) {}
required init!(no: Int) {}
// required init?(no: Int) {}
// required init(no: Int) {}
}
- 一個(gè)協(xié)議可以繼承其他協(xié)議
protocol Runnable {
func run()
}
protocol Livable : Runnable {
func breath()
}
class Person : Livable {
func breath() {}
func run() {}
}
- 協(xié)議組合艺蝴,可以包含1個(gè)類類型(最多1個(gè))
protocol Livable {}
protocol Runnable {}
class Person {}
// 接收Person或者其子類的實(shí)例
func fn0(obj: Person) {}
// 接收遵守Livable協(xié)議的實(shí)例
func fn1(obj: Livable) {}
// 接收同時(shí)遵守Livable猬腰、Runnable協(xié)議的實(shí)例
func fn2(obj: Livable & Runnable) {}
// 接收同時(shí)遵守Livable、Runnable協(xié)議猜敢、并且是Person或者其子類的實(shí)例
func fn3(obj: Person & Livable & Runnable) {}
typealias RealPerson = Person & Livable & Runnable
// 接收同時(shí)遵守Livable姑荷、Runnable協(xié)議、并且是Person或者其子類的實(shí)例
func fn4(obj: RealPerson) {}
- 讓枚舉遵守協(xié)議缩擂,可以實(shí)現(xiàn)遍歷枚舉值
enum Season : CaseIterable {
case spring, summer, autumn, winter
}
let seasons = Season.allCases
print(seasons.count) // 4
for season in seasons {
print(season)
} // spring summer autumn winter
- 遵守CustomStringConvertible厢拭、 CustomDebugStringConvertible協(xié)議,都可以自定義實(shí)例的打印字符串
class Person : CustomStringConvertible, CustomDebugStringConvertible {
var age = 0
var description: String { "person_\(age)" }
var debugDescription: String { "debug_person_\(age)" }
}
var person = Person()
print(person) // person_0
debugPrint(person) // debug_person_0
print調(diào)用的是CustomStringConvertible協(xié)議的description
debugPrint撇叁、po調(diào)用的是CustomDebugStringConvertible協(xié)議的debugDescription
- Swift提供了2種特殊的類型:
Any:可以代表任意類型(枚舉供鸠、結(jié)構(gòu)體、類陨闹,也包括函數(shù)類型)
AnyObject:可以代表任意類類型(在協(xié)議后面寫上: 代表只有類能遵守這個(gè)協(xié)議)
在協(xié)議后面寫上: 也代表只有類能遵守這個(gè)協(xié)議
var stu: Any = 10
stu = "Jack"
stu = Student()
// 創(chuàng)建1個(gè)能存放任意類型的數(shù)組
// var data = Array<Any>()
var data = [Any]()
data.append(1)
data.append(3.14)
data.append(Student())
data.append("Jack")
data.append({ 10 })
- is用來判斷是否為某種類型楞捂,as用來做強(qiáng)制類型轉(zhuǎn)換
protocol Runnable { func run() }
class Person {}
class Student : Person, Runnable {
func run() {
print("Student run")
}
func study() {
print("Student study")
}
}
var stu: Any = 10
print(stu is Int) // true
stu = "Jack"
print(stu is String) // true
stu = Student()
print(stu is Person) // true
print(stu is Student) // true
print(stu is Runnable) // true
var stu: Any = 10
(stu as? Student)?.study() // 沒有調(diào)用study
stu = Student()
(stu as? Student)?.study() // Student study
(stu as! Student).study() // Student study
(stu as? Runnable)?.run() // Student run
var data = [Any]()
data.append(Int("123") as Any)
var d = 10 as Double
print(d) // 10.0
是一個(gè)元類型(metadata)的指針,metadata存放著類型相關(guān)信息
屬于類型
class Person {}
class Student : Person {}
var perType: Person.Type = Person.self
var stuType: Student.Type = Student.self
perType = Student.self
var anyType: AnyObject.Type = Person.self
anyType = Student.self
public typealias AnyClass = AnyObject.Type
var anyType2: AnyClass = Person.self
anyType2 = Student.self
var per = Person()
var perType = type(of: per) // Person.self
print(Person.self == type(of: per)) // true
class Animal { required init() {} }
class Cat : Animal {}
class Dog : Animal {}
class Pig : Animal {}
func create(_ clses: [Animal.Type]) -> [Animal] {
var arr = [Animal]()
for cls in clses {
arr.append(cls.init())
}
return arr
}
print(create([Cat.self, Dog.self, Pig.self]))
import Foundation
class Person {
var age: Int = 0
}
class Student : Person {
var no: Int = 0
}
print(class_getInstanceSize(Student.self)) // 32
print(class_getSuperclass(Student.self)!) // Person
print(class_getSuperclass(Person.self)!) // Swift._SwiftObject
從結(jié)果可以看得出來趋厉,Swift還有個(gè)隱藏的基類: Swift._SwiftObject
可以參考Swift源碼:https://github.com/apple/swift/blob/master/stdlib/public/runtime/SwiftObject.h
- Self代表當(dāng)前類型
class Person {
var age = 1
static var count = 2
func run() {
print(self.age) // 1
print(Self.count) // 2
}
}
- Self一般用作返回值類型寨闹,限定返回值跟方法調(diào)用者必須是同一類型(也可以作為參數(shù)類型)
protocol Runnable {
func test() -> Self
}
class Person : Runnable {
required init() {}
func test() -> Self { type(of: self).init() }
}
class Student : Person {}
var p = Person()
// Person
print(p.test())
var stu = Student()
// Student
print(stu.test())