Swift进阶(十一)协议 & 元类型

协议(Protocol)

  • 协议可以用来定义方法属性下标的声明,协议可以被枚举结构体遵守(多个协议之间用逗号隔开)
protocol Test {
    func fun()
    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 {}
  • 协议中定义方法时不能有默认参数值
  • 默认情况下,协议中定义的内容必须全部实现

协议中的属性

  • 协议中定义属性时,必须用var关键字
  • 实现协议时,属性的权限不能小于协议中定义的属性权限
    ① 协议定义getset,则用var存储属性 或者 get、set计算属性去实现
    ② 协议定义get,用任何属性都可以实现
    eg:
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
    var y: Int = 0
    
    func draw() { print("Person draw") }
    
    subscript(index: Int) -> Int {
        get { index }
        set {}
    }
}

/*-----或者-----*/

class Person: Drawable {
    var x: Int {
        get { 0 }
        set {}
    }
    var y: Int { 0 }
    
    func draw() { print("Person draw") }
    
    subscript(index: Int) -> Int {
        get { index }
        set {}
    }
}

static、class

  • 为了保证通用,协议中必须使用static定义类型方法类型属性类型下标
    因为class修饰的类型相关的事物,只能被适用与结构体枚举无法使用。
protocol Drawable {
    static func draw()
}

class Person1: Drawable {
    static func draw() {
        print("Person1 draw")
    }
}

struct Person2: Drawable {
    static func draw() {
        print("Person2 draw")
    }
}
  • 如果说,父类遵守了某个协议,子类想要去重写协议方法,那么在父类中,协议方法就要用class来修饰,否则就要static来修饰。
protocol Drawable {
    static func draw()
}

class Person1: Drawable {
    class func draw() {
        print("Person1 draw")
    }
}

class Person2: Person1 {
    override class func draw() {
        print("Person2 draw")
    }
}

mutating

  • 只有将协议中的实例方法标记为mutating,才允许结构体枚举的具体实现修改自身内存。
  • \color{orange}{实现方法时}不用加mutating枚举结构体才需要加mutating
protocol Drawable {
    mutating func draw()
}

class Person1: Drawable {
    var x = 0
    func draw() {
        x += 1
    }
}

struct Point: Drawable {
    var x = 0
    mutating func draw() {
        x += 1
    }
}

init

  • 协议中还可以定义初始化器init,非final类实现时必须加上required
    因为final修饰的类,表明该类不能被继承,则不用担心子类不实现init的问题
protocol Drawable {
    init(x: Int, y: Int)
}

class Person1: Drawable {
    required init(x: Int, y: Int) {}
}

final class Person2: Drawable {
    init(x: Int, y: Int) {}
}
  • 如果从协议中实现的初始化器,刚好是重写了父类的指定初始化器,那么这个初始化必须同时加上requiredoverride
protocol Drawable {
    init(x: Int, y: Int)
}

class Person {
    init(x: Int, y: Int) {}
}

class Man: Person, Drawable {
    required override init(x: Int, y: Int) {}
}

init、init?、init!

  • 协议中定义的init?init!,可以用initinit?init!去实现
  • 协议中定义的init,可以用initinit!去实现
protocol Drawable {
    init()
    init?(x: Int)
    init!(y: Int)
}

class Person: Drawable {
    required init() {}
//    required init!() {}
    
    required init?(x: Int) {}
//    required init!(x: Int) {}
//    required init(x: Int) {}
    
    required init!(y: Int) {}
//    required init?(y: Int) {}
//    required init(y: Int) {}
}

协议的继承

  • 一个协议可以继承其他协议
protocol Runnable {
    func run()
}

protocol Livable: Runnable {
    func breath()
}

class Person: Livable {
    func breath() {}
    func run() {}
}

协议的组合

  • 协议组合的时候,可以包含1个类类型(最多1个)
protocol Runnable {}
protocol Livable {}
class Person {}

// 接收Person 或 其子类的实例
func fn0(obj: Person) {}

// 接收遵守 Livable协议 的实例
func fn1(obj: Livable) {}

// 接收同时遵守 Livable、Runable协议 的实例
func fn2(obj: Livable & Runnable) {}

// 接收同时遵守 Livable、Runable协议,并且是 Person 或者 其子类的实例
func fn3(obj: Person & Livable & Runnable) {}

typealias RealPerson = Person & Livable & Runnable
// 接收同时遵守 Livable、Runable协议,并且是 Person 或者 其子类的实例
func fn4(obj: RealPerson) {}

CaseIterable

  • 让枚举遵守CasIterable协议,可以实现遍历枚举值
enum Season: CaseIterable {
    case spring, summer, autumn, winter
}
let seasons = Season.allCases // [Season]
for season in seasons {
    print(season)
}
/*输出结果*/
spring
summer
autumn
winter

我们可以看一下CaseIterable里面的内容

/// The compiler can automatically provide an implementation of the
/// `CaseIterable` requirements for any enumeration without associated values
/// or `@available` attributes on its cases. The synthesized `allCases`
/// collection provides the cases in order of their declaration.
///
/// You can take advantage of this compiler support when defining your own
/// custom enumeration by declaring conformance to `CaseIterable` in the
/// enumeration's original declaration. The `CompassDirection` example above
/// demonstrates this automatic implementation.
public protocol CaseIterable {

    /// A type that can represent a collection of all values of this type.
    associatedtype AllCases : Collection where Self == Self.AllCases.Element

    /// A collection of all values of this type.
    static var allCases: Self.AllCases { get }
}

可以看到allCases是一个可读的类型属性,通过官方给的注释,可以知道allCases是所有值的集合,那么在 当前情况下:
Season.allCases就等价于[Season.spring, Season.summer, Season.autumn, Season.winter]

CustomStringConvertible

  • 遵守CustomStringConvertibleCustomDebugStringConvertible协议,都可以自定义实例的打印字符串
// 遵守 CustomStringConvertible & CustomDebugStringConvertible 协议
class Person: CustomStringConvertible, CustomDebugStringConvertible {
    var age = 0
    var description: String { "person_\(age)" }
    var debugDescription: String { "debug_person_\(age)" }
}

var person = Person()
print(person)
debugPrint(person)

print("------------------------------------")

// 不遵守 CustomStringConvertible & CustomDebugStringConvertible 协议
class Man {
    var age = 10
}
var man = Man()
print(man)
debugPrint(man)
/*输出结果*/
person_0
debug_person_0
------------------------------------
test.Man
test.Man
  • print调用的是CustomStringConvertible协议的description
  • debugPrintpo调用的是CustomDebugStringConvertible协议的debugDescription

我们来看一下控制台的po

image.png

Any、AnyObject

  • Swift 提供了两种特殊的类型:AnyAnyObject
    Any:可以代表任意类型(枚举、结构体、类,也包括函数类型)
    AnyObject:可以代表任意类型(在协议后面写上:AnyObject代表只有类能遵守这个协议)。另外,在协议后面写上:class也代表只有能遵守这个协议。

is、as?、as!、as

  • is用来判断是否为某种类型,as用来强制类型转换
protocol Runnable {
    func run()
}
class Person {}
class Man: Person, Runnable {
    func run() {
        print("Man run")
    }
    
    func sleep() {
        print("Man sleep")
    }
}

我们先看一下is的使用

var m: Any = 10
print(m is Int) // true

m = "Tom"
print(m is String) // true

m = Man()
print(m is Person) // true
print(m is Man) // true
print(m is Runnable) // true

我们再来看一下as?as!是如何用的
as? 表示转化可能成功,也可能失败。
as! 表示强制解包(注意:强制解包是有风险的)

var m: Any = 10
(m as? Man)?.sleep() // 没有调用sleep

m = Man()
(m as? Man)?.sleep() // Man sleep
(m as! Man).sleep() // Man sleep
(m as? Runnable)?.run() // Man run

那我们来看一下这一句代码

(m as? Man)?.sleep()

① 首先as? 表示转化可能成功,也可能失败。
② 紧接着第二个?是我们上一篇文章讲到的可选链的内容,如果前面的为nil后面的就不会执行。

我们再来看一下as
as\color{orange}{百分之一百}可以转换成功的时候使用

var list = [Any]()
list.append(Int("123") as Any)

var num = 10 as Double
print(num) // 10.0

X.self、X.Type、AnyClass

  • X.self是一个元类型(metadata)的指针,metadata存放着类型相关的信息
  • X.self属于X.Type类型
    这里大家要注意,实例对象在堆内存中存放的前8个字节就是类型信息。而且X.self就是8个字节,和实例对象在堆内存中存放的前8个字节是一样的。
    下面我们来证明一下:
class Person {}

var p: Person = Person() // 注意:此处打上断点,进入汇编查看汇编代码
var pType: Person.Type = Person.self

首先我们来证明一下X.self是8个字节

image.png

结合Xcode注释和movq指令可以断定X.self占8个字节(q代表8个字节,常用的汇编指令大家可以网上搜一下)
接下来我们再找一下pType里面存放的内容是什么:
我们由下往上推论
image.png

那么我们可以在第12行处,打断点,看一下%rax 里面存放的是什么
image.png

可以看到Xcode也给出了答案,此时%rax里面存放的就是metadata信息。
那么接下来我们再看一下p里面存放的信息:
image.png

可以看到p在堆内存里面的前8个字节的内容和pType一模一样。因此我们上面的推论是正确的。

下面我们看一下继承的关系

class Person {}
class Student: Person {}
var perType: Person.Type = Person.self
var stuType: Student.Type = Student.self
// 注意这样做是可以的,因为X.Type也是一个类型,并且Student继承自Person
// 从赋值角度看:perType 和 stuType 都是8个字节,也没什么问题
// 另外需要注意的是,这里如果把Student改成跟Person没有关系的其他类,比如Dog,就会报错,这样做是不允许的
perType = Student.self
var anyType: AnyObject.Type = Person.self
anyType = Student.self

public typealias AnyClass = AnyObject.Type
var anyType2: AnyClass = perType.self
anyType2 = Student.self

我们再看一个语法糖 type(of: <#T##T#>)

var per = Person()
var perType = type(of: per) // Person.self
print(Person.self == type(of: per)) // true
  • \color{red}{这里大家要注意一下:}
    ① 从汇编代码来看 type(of: <#T##T#>)并不是一个函数调用,只是看起来像一个函数,这里大家可以通过汇编来查看一下,会发现其对应的并不是call指令。(大家可以自行查看一下)
    image.png

\color{red}{但是}通过Xcode的提示,type(of: <#T##T#>)又是一个函数,见下图:

image.png

具体原因,我暂时也不清楚,这里大家可以自行探索一下。之后弄明白了再给大家补上。

元类型的应用

  • 比如开发中 tabbar的配置,就可以利用元类型来做。
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])

下面我们来看一个小知识点

image.png

从打印结果,大家可以看到:
Person好像还有一个父类,但是根据Swift的文档,Swift的类并没有统一的基类,并且从代码看Person也没有继承自任何类。所以这里我们可以猜测,在Swift库里面应该还有一个隐藏的基类的。当然这个我们后续再验证,有兴趣的同学可以在Swift源码里面找一下。

Self

  • Self代表当前类型
class Person {
    var age: Int = 0
    static var count = 2
    func fun() {
        print(self.age) // 0
        print(Self.count) // 2
    }
}
  • Self一般用作返回值类型,限定返回值跟方法调用者必须是同一类型(也可以作为参数类型),类似于OC的instancetype
protocol Runnable {
    func test() -> Self
}

class Person: Runnable {
    func test() -> Self {
        type(of: self).init()
    }
    
    required init() {}
}
class Student: Person {}

var p = Person()
print(p.test()) // Person

var s = Student() // Student
print(s.test())
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,185评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,652评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,524评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,339评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,387评论 6 391
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,287评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,130评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,985评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,420评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,617评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,779评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,477评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,088评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,716评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,857评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,876评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,700评论 2 354

推荐阅读更多精彩内容