Swift协议和扩展,我需要根据需要调用重写方法或默认扩展方法

Pan*_*waj 6 protocols ios swift

我有一个协议Vehicle及其扩展如下:

protocol Vehicle {
    func Drive()    
}

extension Vehicle {
    func Stop() {
        print("iiiich...")
    }
}
Run Code Online (Sandbox Code Playgroud)

对于Stop Method,我也有以下声明

struct Car: Vehicle {
    func Drive() {
        print("Can Drive")
    }
    func Stop() {
        print("yo stop")
    }
}

let myCar = Car()
myCar.Drive()
myCar.Stop()
Run Code Online (Sandbox Code Playgroud)

但它覆盖了停止方法

// Output
// Can Drive
// yo stop
Run Code Online (Sandbox Code Playgroud)

根据我的要求,我需要一段时间的默认方法和一些时间覆盖的方法定义

Pan*_*waj 8

嘿我得到的答案是通过对象调用你的默认方法而不是overriddedn来符合协议,所以我们可以根据需要调用两个定义

let honda: Vehicle = Car()
honda.Drive()
honda.Stop()
// Output
// Can Drive
// iiiich..
Run Code Online (Sandbox Code Playgroud)

当我们创建一个没有类型的变量时,当对象仅符合协议时,这是静态分派.


Swe*_*per 5

如果需要协议扩展中声明的方法,只需使编译器认为car的类型为Vehicle

let myCar = Car()
(myCar as Vehicle).Stop()
Run Code Online (Sandbox Code Playgroud)