gpt4 book ai didi

arrays - Swift:在扩展中声明一个类型的数组符合协议(protocol)

转载 作者:搜寻专家 更新时间:2023-11-01 07:29:01 25 4
gpt4 key购买 nike

我已经声明了一个名为“Validates”的协议(protocol),用于验证字符串。我已经将它添加到所有带有扩展名的字符串中。代码看起来像这样,并且运行良好:

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

最佳答案

如果我理解正确你想做什么,你必须像这样调用协议(protocol)方法:

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

然后你需要像这样制作你的扩展:

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

关于arrays - Swift:在扩展中声明一个类型的数组符合协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33877145/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com