【发布时间】:2015-09-16 12:38:15
【问题描述】:
我正在尝试提供协议的默认实现,以便它可以满足来自其他协议的多个约束。
鉴于以下协议:
public protocol Creature {
var name: String { get }
var canMove: Bool { get }
}
public protocol Animal: Creature {}
public protocol Moveable {
var movingSpeed: Double { get set }
}
public protocol Agend {
var aged: Int { get }
}
我可以在 Self 上使用单个条件进行扩展:
// all animals can move
extension Moveable where Self: Animal {
public var canMove: Bool { return true }
}
但是如何设置约束来为同时符合Animal 和Aged 协议的类型提供默认的Moveable 实现?像下面这样的东西?还是 where 子句有一些“添加”“或”选项?
// Pseudocode which doesn't work
extension Moveable where Self: Animal && Self: Aged {
public var canMove: Bool { return true }
}
【问题讨论】:
-
顺便说一下,要查看我编写的最终代码示例,请访问:audreyli.me/2015/06/29/…