简体   繁体   中英

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

I have declare a protocol called 'Validates', which validates strings. I've added this to all Strings with an extension. The code looks like this, and it's working fine:

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

I've omitted a couple of things, but you get the gist.

The next step is to do the same for arrays of strings. Ideally I'd like to create an extension which declares that given an collection of things that Validate, the collection itself should also validate. Failing that, since this is just working on Strings at the moment can I just declare that any array of Strings validates.

I've tried this but I can't get it to compile.

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

if I understand correctly what you want to do and you have to call the protocol method like this:

let testArray: [String] = ["str1", "str2", "str3"]
testArray.protocolMethod()

Then you need make your extention like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM