Arrays Swift:在扩展中声明类型的数组符合协议
我声明了一个名为“Validates”的协议,它验证字符串。我已将其添加到具有扩展名的所有字符串中。代码如下所示,工作正常:Arrays Swift:在扩展中声明类型的数组符合协议,arrays,swift,generics,protocols,extension-methods,Arrays,Swift,Generics,Protocols,Extension Methods,我声明了一个名为“Validates”的协议,它验证字符串。我已将其添加到具有扩展名的所有字符串中。代码如下所示,工作正常: protocol Validates { func validateWithRules(rules: [Rule]) throws } extension String: Validates { func validateWithRules(rules: [Rule]) throws { var validationErrors =
protocol Validates {
func validateWithRules(rules: [Rule]) throws
}
extension String: Validates {
func validateWithRules(rules: [Rule]) throws {
var validationErrors = [RuleFailError]()
for aRule in rules {
do {
try aRule.validate(self)
}
catch let error as RuleFailError {
validationErrors.append(error)
}
}
if validationErrors.count > 0 {
throw ValidationError(ruleErrors: validationErrors)
}
}
}
我省略了几件事,但你明白要点了
下一步是对字符串数组执行相同的操作。理想情况下,我想创建一个扩展,声明给定一个验证的集合,集合本身也应该验证。如果做不到这一点,因为目前这只是在处理字符串,所以我可以声明任何字符串数组都可以进行验证
我已经试过了,但无法编译
extension CollectionType where Generator.Element == Validates: Validates {
func validateWithRules(rules: [Rule]) throws {
var validationErrors = [RuleFailError]()
for anItem in self {
do {
try anItem.validateWithRules(rules)
}
catch let error as ValidationError {
for failedRule in error.ruleErrors {
validationErrors.append(failedRule)
}
}
catch {}
if validationErrors.count > 0 {
throw ValidationError(ruleErrors: validationErrors)
}
}
}
}
如果我正确理解了您要执行的操作,您必须像这样调用协议方法:
let testArray: [String] = ["str1", "str2", "str3"]
testArray.protocolMethod()
extension CollectionType where Generator.Element: Validates {
...
}
然后您需要将您的扩展名设置为这样:
let testArray: [String] = ["str1", "str2", "str3"]
testArray.protocolMethod()
extension CollectionType where Generator.Element: Validates {
...
}
我可能错了,但我认为这目前是不可能的。比较,了解有关类似问题的讨论,该问题是数组
如果其元素是可均衡的
,则不能符合可均衡的
。