美文网首页
associatedtype 联想类型

associatedtype 联想类型

作者: fordring2008 | 来源:发表于2017-02-04 09:23 被阅读76次

// 待改良版

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

}

}

相关文章

  • associatedtype 联想类型

    // 待改良版 protocol Food { } protoco lAnimal { func eat(_foo...

  • Swift 小札

    associatedtype associatedtype用于在protocol中代指一个确定类型并要求该类型实现...

  • 2018-03-08

    Swift关键字 associatedtype: 协议-关联类型, 作用:为协议中的某个类型提供了一个占位名(或者...

  • 11.Swift4特性/独占访问权限、where和associa

    独占内存访问权限 associatedtype 关键字后可用where约束,使用where约束后的协议遵守的类型内...

  • Swift 关键字 -- associatedtype

    associatedtype 关联类型的关键字,处理 协议 中的范型使用场景 实现 Stack 协议 错误例子: ...

  • swift的protocol带有associatedtype

    当protocol中带有associatedtype或者Self约束时,这个协议就不能被当作一个独立的类型使用了,...

  • associatedtype

    从字面上来理解,就是相关类型。意思也就是被associatedtype关键字修饰的变量,相当于一个占位符,而不能表...

  • Swift associatedtype

    在协议中除了定义属性和方法外,我们还能定义类型的占位符,让实现协议的类型来指定具体的类型。 添加 associat...

  • POP网络重构(二)

    模型 结构体LGPerson,扩展了LGDecodable协议,具备了parse能力 associatedtype...

  • Swift: typealias、associatedtype

    typealias的用法: typealias是给现有的类型(包括系统和自定义的)进行重新命名,然后就可以用该别名...

网友评论

      本文标题:associatedtype 联想类型

      本文链接:https://www.haomeiwen.com/subject/qusjittx.html