如何解决 Swift 协议的规范问题
How to solve the specification problem for Swift Protocol
protocol Specification {
associatedtype T
func isSatisfied(item : T) -> Bool
}
protocol AndSpecification {
associatedtype T
var arrayOfSpecs : [Specification] {set}
}
上述代码出现如下错误
Protocol 'Specification' can only be used as a generic constraint
because it has Self or associated type requirements
我了解到这个问题是因为关联类型,如果我添加一个where子句就可以解决这个问题。但是我不知道我应该在哪里以及如何使用这个 where 子句
您认为您需要一个 where
子句,因为您希望数组包含具有相同 T
的 Specification
,对吧?好吧,具有关联类型的协议也不能做到这一点!
您可以做的是让数组包含所有相同类型的规范:
protocol AndSpecification {
associatedtype SpecificationType : Specification
var arrayOfSpecs : [SpecificationType] { get }
}
如果您真的喜欢您的 T
关联类型,您仍然可以添加一个:
protocol AndSpecification {
associatedtype T
associatedtype SpecificationType : Specification where SpecificationType.T == T
var arrayOfSpecs : [SpecificationType] { get }
}
但这很多余,因为你可以直接说 AndSpecification.SpecificationType.T
。
protocol Specification {
associatedtype T
func isSatisfied(item : T) -> Bool
}
protocol AndSpecification {
associatedtype T
var arrayOfSpecs : [Specification] {set}
}
上述代码出现如下错误
Protocol 'Specification' can only be used as a generic constraint because it has Self or associated type requirements
我了解到这个问题是因为关联类型,如果我添加一个where子句就可以解决这个问题。但是我不知道我应该在哪里以及如何使用这个 where 子句
您认为您需要一个 where
子句,因为您希望数组包含具有相同 T
的 Specification
,对吧?好吧,具有关联类型的协议也不能做到这一点!
您可以做的是让数组包含所有相同类型的规范:
protocol AndSpecification {
associatedtype SpecificationType : Specification
var arrayOfSpecs : [SpecificationType] { get }
}
如果您真的喜欢您的 T
关联类型,您仍然可以添加一个:
protocol AndSpecification {
associatedtype T
associatedtype SpecificationType : Specification where SpecificationType.T == T
var arrayOfSpecs : [SpecificationType] { get }
}
但这很多余,因为你可以直接说 AndSpecification.SpecificationType.T
。