Swift-OOP-Protocol

2020-11-25  本文已影响0人  守护地中海的花
image.png
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 {
    
}

协议中的属性

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

协议中static、class

/**
 * 为了保证通用,协议中必须用static定义类型方法、类型属性、类型下标
 */
protocol Drawablex {
    static func draw()
}
class Personx: Drawablex {
//    static func draw() {
//        print("Personx Draw")
//    }
    class func draw() {
        print("Personx Draw")
    }
    //class static 都可以
}

协议中mutating

protocol Drawablem {
    mutating func draw()
}
class Size: Drawablem {
    var width = 10
    
    func draw() {
        width = 20
    }
}
struct Point:Drawablem {
    var width = 10
    mutating func draw() {
        width = 20 + width
    }
}

协议中的init

protocol Drawablei {
    init(x: Int,y: Int)
}
class Pointi: Drawablei {
    required init(x: Int, y: Int) {
        
    }
}
final class Sizei: Drawablei {
    init(x: Int, y: Int) {
        
    }
}
class originPointi {
    init(x: Int, y: Int) {
        
    }
}
class subPointi: originPointi,Drawablei {
   required override init(x: Int, y: Int) {
        super.init(x: x, y: y)
    }
}

init、init?、init! 不知道用处多不多

protocol Liveable {
    init ()
    init?(age: Int)
    init!(no: Int)
}
class Persona: Liveable {
    required init() {
        
    }
    required init!(no: Int) {
        
    }
    required init?(age: Int) {
        
    }
}

协议的继承

protocol Runnaable {
    func run()
}
protocol Playnaable : Runnaable {
    func breath()
}
class Dog: Playnaable {
    func run() {
        
    }
    func breath() {
        
    }
}

协议的组合

func fn0 (obj: Runnaable & Playnaable) {
    
}

CustomStringConvertible

class Personz: CustomStringConvertible,CustomDebugStringConvertible {
    var age = 0
    var description: String{"person\(age)"}
    var debugDescription: String{"debugPerson\(age)"}
}
let pz = Personz()
print(pz)
debugPrint(pz)
上一篇 下一篇

猜你喜欢

热点阅读