1.用分类来对protocol中的方法进行一些默认实现
protocol Callable {
var number:String {get set}
func call()
}
extension Callable{
func call(){
print("拨打了电话\(self.number)")
}
}
struct IPhone : Callable {
var number: String = "110"
}
var iphone = IPhone()
iphone.call() //打印拨打了电话110
2.覆盖protocol中的默认实现
struct IPhone : Callable {
var number: String = "120"
func call() {
print("用IPhone 8 拨打了电话\(self.number)")
}
}
var iphone = IPhone()
iphone.call() //打印用iphone 8 拨打了电话120
3.一个类中同一个方法有两份方法实现,你见过吗?
我们把call的声明从protocol中去除
protocol Callable {
var number:String {get set}
}
extension Callable{
func call(){
print("拨打了电话\(self.number)")
}
}
struct IPhone : Callable {
var number: String = "119"
func call() {
print("用IPhone 9 拨打了电话\(self.number)")
}
}
var iphone = IPhone()
iphone.call() //打印 用Iphone 9 拨打了电话119
(iphone as Callable).call() //打印 拨打了电话119
4.protocol中的选择性默认实现,6到不能行
protocol Callable {
var number:String {get set}
func call()
}
extension Callable{
func call(){
print("拨打了电话\(self.number)")
}
}
protocol Netable {
var ip :String {get set}
func net()
}
extension Netable{
func net(){
print("我在上网 ip\(self.ip)")
}
}
extension Callable where Self:Netable{
func call(){
print("我在用网络打电话 ip \(self.ip)")
}
}
struct IPhone9 : Callable {
var number: String = "110"
}
struct IPhone10 : Callable,Netable {
var number: String = "110"
var ip: String = "110.110.110.110"
}
var iphone9 = IPhone9()
iphone9.call() //打印 拨打了电话110
var iphone10 = IPhone10()
iphone10.call() //打印 我在用网络打电话 ip 110.110.110.110