Swift:在扩展中声明一个类型的数组符合一个协议

Swift: Declare in an extension that an array of a type conforms to a protocol

我已经声明了一个名为 'Validates' 的协议,它可以验证字符串。我已经将它添加到所有带有扩展名的字符串中。代码如下所示,并且运行良好:

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()

然后你需要这样 extention:

extension CollectionType where Generator.Element: Validates {
    ...
}