14-Swift可选链、协议

1.可选链

  • 如果可选项为nil,调用方法、下标、属性失败,结果为nil
  • 如果可选项不为nil,调用方法、下标、属性成功,结果会被包装成可选项
  • 如果结果本来就是可选项,不会进行再次包装
class Car { var price = 0 }
class Dog { var weight = 0 }
class Person {
    var name: String = ""
    var dog: Dog = Dog()
    var car: Car? = Car()
    func age() -> Int { 18 }
    func eat() { print("Person eat") }
    subscript(index: Int) -> Int { index }
}

var person: Person? = Person()
var age1 = person!.age() // Int
var age2 = person?.age() // Int?
var name = person?.name // String?
var index = person?[6] // Int?

func getName() -> String { "jack" }
// 如果person是nil,不会调用getName()
person?.name = getName()


var dog = person?.dog // Dog?
var weight = person?.dog.weight // Int?
var price = person?.car?.price // Int?

/// 多个?可以链接在一起
/// 如果链中任何一个节点是nil,那么整个链就会调用失败
var scores = ["Jack": [86,82,84], "Rose":[79, 94, 81]]
scores["Jack"]?[0] = 100
scores["Rose"]?[2] += 10
scores["Kate"]?[0] = 88

var num1: Int? = 5
num1? = 10 // Optional(10)

var num2: Int? = nil
num2? = 10 // nil

var dict: [String : (Int, Int) -> Int] = [
    "sum" : (+),
    "difference" : (-)
]
var result = dict["sum"]?(10, 20) // Optional(30), Int?

2.协议

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

3.协议中的属性

  • 协议中定义属性时必须用var关键字
  • 实现协议时的属性权限要不小于协议中定义的属性权限
  • 协议定义get、set,用var存储属性或get、set计算属性去实现
  • 协议定义get,用任何属性都可以实现
class Person: Drawable {
    var x: Int = 0
    var y: Int = 0
    func draw() {
        print("Person draw")
    }
    subscript(index: Int) -> Int {
        set { }
        get { index }
    }
}

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

4.static、class

  • 为了保证通用,协议中必须用static定义类型方法、类型属性、类型下标
protocol Drawable1 {
    static func draw()
}

class Person3 : Drawable1 {
    class func draw() {
         print("person3 draw")
    }
}

class Person4 : Drawable1 {
    static func draw() {
        print("Person4 draw")
    }
}

5.mutating

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

class Size : DrawableProtocol {
    var width: Int = 0
    func draw() {
        width = 10
    }
}

struct Point : DrawableProtocol {
    var x: Int = 0
    mutating func draw() {
        x = 10
    }
}

6.init

/// 协议中还可以定义初始化器init 
/// 非final类实现时必须加上required 
protocol DrawableProtocol1 {
    init(x: Int, y: Int)
}
class PointClass : DrawableProtocol1 {
    required init(x: Int, y: Int) { }
}
final class SizeClass : DrawableProtocol1 {
    init(x: Int, y: Int) { }
}

/// 如果从协议实现的初始化器,刚好是重写了父类的指定初始化器
/// 那么这个初始化必须同时加required、override
protocol Liveable {
    init(age: Int)
}
class TestPerson {
    init(age: Int) {}
}
class Student : TestPerson, Liveable {
    required override init(age: Int) {
        super.init(age: age)
    }
}

7.init、init?、init!

  • 协议中定义的init?、init!,可以用init、init?、init!去实现
  • 协议中定义的init,可以用init、init!去实现
protocol Livable {
    init()
    init?(age: Int)
    init!(no: Int)
}

class Teacher: 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) {}
}

8.协议的继承

  • 一个协议可以继承其他协议
protocol Runable {
    func run()
}
protocol Livable1 : Runable {
      func breath()
}
class Person5 : Livable1 {
      func breath() {}
      func run() {}
}

9.协议组合

/// 协议组合,可以包含1个类类型(最多1个)
protocol LivableTest {}
protocol RunnableTest {}
class PersonTest {}

// 接收PersonTest或者其子类的实例
func fn0(obj: PersonTest) {}
// 接收遵守LivableTest协议的实例
func fn1(obj: LivableTest) {}
// 接收同时遵守LivableTest、RunnableTest协议的实例
func fn2(obj: LivableTest & RunnableTest) {}
// 接收同时遵守LivableTest、RunnableTest协议、并且是PersonTEst或者其子类的实例
func fn3(obj: PersonTest & LivableTest & RunnableTest) {}

typealias RealPerson = PersonTest & LivableTest & RunnableTest
func fn4(obj: RealPerson) {}

10.CaseIterable

  • 让枚举遵守CaseIterable协议,可以实现遍历枚举值
enum Season: CaseIterable {
    case spring, summer, autumn, winter
}

let seasons = Season.allCases
print(seasons.count) // 4
for season in seasons {
    print(season)
} // spring summer autum winter

11.CustomStringConvertible

  • 遵守CustomStringConvertible、 CustomDebugStringConvertible协议,都可以自定义实例的打印字符串
/// 遵循CustomStringConvertible、CustomDebugStringConvertible协议,都可以自定义实例的打印字符串
class TestPerson1 : CustomStringConvertible, CustomDebugStringConvertible {
    var age = 0
    var description: String { "person_\(age)" }
    var debugDescription: String {"debug_person_\(age)"}
}
var person = TestPerson1()
print(person) // person_0
debugPrint(person) // debug_person_0
/// print调用的是CustomStringConvertible协议的description
/// debugPrint、 po调用的是CustomDebugStringConvertible协议的debugDescription

12.Any、AnyObject

  • Swift提供了2中特殊的类型: Any、AnyObject
  • Any: 可以代表任意类型(枚举、结构体、类、也包括函数类型)
  • AnyObject:可以代表任意类类型(在协议后面写上:AnyObject代表只有类能遵守这个协议)
  • 在协议后面写上:class也代表只有类能遵守这个协议
var stu: Any = 10
stu = "Jack"
stu = Student(age: 10)
// 创建1个能存放任意类型的数组
// var data = Array<Any>()
var data = [Any]()
data.append(1)
data.append(3.14)
data.append(stu)
data.append("Jack")
data.append({10})

13.is、as?、as!、 as

  • is用来判断是否为某种类型,as用来强制类型转换
protocol RunnableTest2 { func run() }
class PersonTest2 {}
class StudentTest2 : PersonTest2, RunnableTest {
    func run () {
        print("Stundet run")
    }
    func study() {
        print("Student study")
    }
}

var stu1: Any = 10
print(stu1 is Int) // true
stu1 = "Jack"
print(stu1 is String) // true
stu1 = StudentTest2()
print(stu1 is PersonTest2) // true
print(stu1 is StudentTest2) // true
print(stu1 is RunnableTest2) // true

stu1 = 10
(stu1 as? StudentTest2)?.study() // 没有调用study
stu1 = StudentTest2()
(stu1 as? StudentTest2)?.study() // Student study
(stu1 as! StudentTest2).study() // Student study
(stu1 as? RunnableTest2)?.run() // Student run

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

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

14.X.self、X.Type、AnyClass

  • X.self是一个元类型(metadata)的指针,metadata存放着类型相关信息
  • X.self属于X.Type类型
class PersonTest3 {}
class StudentTest3 : PersonTest3 {}
var perType: PersonTest3.Type = PersonTest3.self
var stuType: StudentTest3.Type = StudentTest3.self
perType = StudentTest3.self

var anyType: AnyObject.Type = PersonTest3.self
anyType = StudentTest3.self

//public typealias AnyClass = AnyObject.Type
var anyType2: AnyClass = PersonTest3.self
anyType2 = StudentTest3.self

var per = PersonTest3()
perType = type(of: per)
print(PersonTest3.self == perType)

15.元类型的应用

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]))

print(class_getInstanceSize(Cat.self)) // 16
print(class_getSuperclass(Cat.self)!) // Animal
print(class_getSuperclass(Animal.self)!) // Swift._SwiftObject

16.Self

  • Self代表当前类型
  • Self一般用作返回值类型,限定返回值跟方法调用者必须是同一类型(也可以作为参数类型)
/// Self代表当前类型
class PersonTest4 {
    var age = 1
    static var count = 2
    func run() {
        print(self.age) // 1
        print(Self.count) // 2
    }
}

protocol Runnable {
    func test() -> Self
}
class PersonTest5 : Runnable {
    required init () {}
    func test() -> Self { type(of: self).init() }
}
class StudentTest5 : PersonTest5 {}

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

var stuTest = StudentTest5()
// Student
print(stuTest.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

推荐阅读更多精彩内容