Swift 2 学习笔记 18.协议

课程来自慕课网liuyubobobo老师


协议
  • 协议基础
protocol Pet{
    var name: String{get set}
    var birthPlacs: String{get}
    
    func playWith()
}

class Dog: Pet {
    var name: String = "Wangcai"
    var birthPlacs: String = "Beijing"
    
    func playWith() {
        print("Wong!")
    }
}

var myDog: Dog = Dog()
myDog.birthPlacs = "Shanghai"

var aPet: Pet = myDog
//aPet.birthPlacs = "Hangzhou"  // get-only
  • 协议和构造函数
protocol Pet{
    var name: String{get set}
    
    init(name: String)
    
    func playWith()
}

class Animal {
    var type: String = "mammal"
}

class Dog: Animal, Pet {
    var name: String = "Wangcai"
    
    required init(name: String) {
        self.name = name
    }
    
    func playWith() {
        print("Wong!")
    }
}

class Bird: Animal {
    var name: String = "Bird"
    
    init(name: String) {
        self.name = name
    }
}

class Parrot: Bird, Pet {
    
    required override init(name: String) {
        super.init(name: "Parrot " + name)
    }
    
    func playWith() {
        print("Hello")
    }
}
  • 为什么要用协议


  • 类型别名(typealias)和关联类型(associatedtype)

typealias Length = Double

extension Double {
    var km: Length { return self*1000 }
    var m: Length { return self }
    var cm: Length { return self / 100 }
    var ft: Length { return self / 3.28084 }
}

let runningDistance: Length = 3.54.km
protocol WeightCalculable {
    associatedtype WeightType
    var weight: WeightType { get }
}

class iPhone7: WeightCalculable {
    typealias WeightType = Double
    var weight: WeightType  = 0.114
}

class Ship: WeightCalculable {
    typealias WeightType = Int
    
    var weight: WeightType
    
    init(weight: WeightType) {
        self.weight = weight
    }
}

let ticnic = Ship(weight: 46_328_000)
  • 标准库中的常用协议
// Equatable: 可判断是否相等
// Comparable: 可进行比较运算
// CustomStringConvertible: 自定义表示文字

你可能感兴趣的:(Swift 2 学习笔记 18.协议)