Swift 2 学习笔记 18.协议

2018-11-26  本文已影响0人  Maserati丶

课程来自慕课网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 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: 自定义表示文字
上一篇 下一篇

猜你喜欢

热点阅读