associatedtype 联想类型

2017-02-04  本文已影响76人  fordring2008

// 待改良版

protocol Food { }

protoco lAnimal {

func eat(_food :Food)

}

struct Meat:Food{ }

struct Grass:Food{}

struct Tiger:Animal{

funceat(_food:Food) {//实现协议

//这里只有在运行时才能检查到,需要改进,如果通过修改eat方法的参数,就会出现编译失败

if food is Meat{

print("eat\(food) ")

}else{

fatalError("Tiger can only eat meat!")

}

}

}

let meat =Meat()

Tiger().eat(meat)

//方法参数的类型先不固定,来让实现协议的类或者结构体定义,但是代价是不能被当做独立的类型使用了

protocol Animal {

associatedtype F

func eat(_food : F)

}

struct Tiger:Animal{

func eat(_food:Meat) {//实现协议

print("eat\(food) ")

}

}

struct Sheep:Animal{

func eat(_food:Grass) {

print("eat\(food) ")

}

}

Tiger().eat(Meat())

Sheep().eat(Grass())

// Animal中包含了未确定类型,早成下面的代码出错

//原因:在一个协议中加入了像是associatedtype或者Self的约束后,它将只能被用为泛型约束,而不能作为独立的类型使用,也失去了动态派发的特性

func isDangerous(animal:Animal) ->Bool{//错误代码

if animal is Tiger{

return true

}else{

return false

}

}

//将函数改为泛型函数就可以了

func isDangerous1(animal:T) ->Bool{

if animal isTiger{

return true

}else{

return false

}

}

上一篇 下一篇

猜你喜欢

热点阅读