美文网首页Swift好文收藏
swift的protocol带有associatedtype

swift的protocol带有associatedtype

作者: 逗留 | 来源:发表于2018-10-10 14:36 被阅读31次

当protocol中带有associatedtype或者Self约束时,这个协议就不能被当作一个独立的类型使用了,例如:
在没有这些约束的时候,我们可以这样写:

protocol Food {}
protocol Animal {
  func eat(_ food: Food)
}
func isDangerous(animal: Animal) -> Bool {
  if animal is Tiger {
    return true
  }
  return false
}

但是如果给Animal添加了associatedtype

protocol Animal {
  associatedtype F: Food
  func eat(_ food: F)
}

此时在写出上面isDangerous的代码时,回报错

protocol 'Animal' can only be used as a generic constraint because it has Selfor associated type requirements

这是因为 Swift 需要在编译时确定所有类型,这里因为Animal包含了一个不确定的类型,所以随着Animal本身类型的变化,其中的F将无法确定 (试想一下如果在这个函数内部调用eat的情形,你将无法指定eat参数的类型)。在一个协议加入了像是associatedtype或者Self的约束 后,它将只能被用为泛型约束,而不能作为独立类型的占位使用,也失去了动态派发的特性。也 就是说,这种情况下,我们需要将函数改写为泛型:

func isDangerous<T: Animal>(animal: T) -> Bool {
  if animal is Tiger {
    return true
  }
  return false
}

相关文章

  • swift的protocol带有associatedtype

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

  • Swift 小札

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

  • Swift associatedtype

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

  • Swift: typealias、associatedtype

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

  • Swift中associatedtype

  • swift - associatedtype的妙用

    开发中你经常能遇到这样的业务场景.许多列表视图表格数据格式差不多.你会设计很多的协议里面包含各种数据源的类型(取名...

  • swift关键字全集

    >>>Swift中所有关键字分类: 用在声明中的关键字: associatedtype 、 class 、 dei...

  • swift中的协议和扩展

    1.Swift中的Protocol 什么是Protocol? Protocol是Swift中的一种自定义类型,可以...

  • Swift小知识

    1. 关于Swift中Protocol 1. 在 Swift 中,Delegate 就是基于 Protocol 实...

  • Swift 5.0-typealias与associatedty

    Swift 中关键字typealias重命名与associatedtype关联对象,在实际开发中比较常见。 typ...

网友评论

    本文标题:swift的protocol带有associatedtype

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