热门搜索 :
考研考公
您的当前位置:首页正文

Swift 协议作为类型使用

来源:东饰资讯网

协议作为类型使用:可用于参数类型/返回类型;变量/常量/属性;集合类型中的元素类型

protocol RunProtocol {
    func runDistance(speed:Int) -> Int
}


struct People:RunProtocol {
    func runDistance(speed:Int) ->Int{
        return speed*100        
    }
}

class Dog :RunProtocol {
    func runDistance(speed:Int) ->Int{
        return speed*100        
    }
}

//跑步游戏
struct RunGame {
    var time:Int
    var runProtocol:RunProtocol   //协议作为属性
    var speed:Int
    func run() -> Int {
         return time*self.runProtocol.runDistance(speed:self.speed)
     }
}

let peopleGame = RunGame(time:20,runProtocol:People(),speed:2)
//let dogGame = RunGame(time:20,runProtocol:Dog(),speed:4)
print(game.run())

由上面的例子可以看出,无论结构体还是类,只要是实现了跑步协议,实现了其方法,其实例化都可以作为此协议充当跑步游戏的协议属性,去调用各自协议的实现方法

Top