我正在尝试提供协议的默认实现,以满足其他协议的多个约束条件。
给定以下协议:
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 }
}