Swift中如何传入遵循协议的类型作为函数参数?
Swift中传递遵循协议的类类型作为函数参数的解决方案
初始实现代码
我想要实现的示例代码如下:
protocol PredicateBuilder { static func getpredicate(value: String)->NSCompoundPredicate? } class ExampleClass1: PredicateBuilder { static func getpredicate(value: String)->NSCompoundPredicate? { // ... 创建谓词逻辑 return predicate } } class ExampleClass2: PredicateBuilder { static func getpredicate(value: String)->NSCompoundPredicate? { //... 创建谓词逻辑 return predicate } } class CLAUSEPARSER { static func getPredicate(searchClause: String, predicateBuilder: BuilderClass) -> NSCompoundPredicate? { // ... 解析searchClause并构建复合谓词 for word in searchClause { let predicate = predicateBuilder.getpredicate(value: word) // 后续处理... } return theCompoundPredicate } } func main() { let predicate1 = CLAUSEPARSER.getPredicate(searchClause: searchString, predicateBuilder: ExampleClass1) let array1 = [ExampleClass1]() // ...填充数组 let filteredArray1 = array1.filter({predicate1.evalute(with: $0)}) let predicate2 = CLAUSEPARSER.getPredicate(searchClause: searchString, predicateBuilder: ExampleClass2) let array2 = [ExampleClass2]() // ...填充数组 let filteredArray2 = array2.filter({predicate2.evalute(with: $0)}) }
遇到的问题
不知道该怎么定义CLAUSEPARSER.getPredicate函数里的predicateBuilder参数——我需要传递的是遵循PredicateBuilder协议的类本身,而不是类的实例。
找到的解决方案
通过协议的Type类型来定义参数,就能实现需求:
修改后的函数定义
static func getPredicate(searchClause: String, predicateBuilder: PredicateBuilder.Type) -> NSCompoundPredicate?
调用方式
调用函数时,传入类的.self来传递类类型:
let predicate2 = CLAUSEPARSER.getPredicate(searchClause: searchString, predicateBuilder: ExampleClass2.self)
内容的提问来源于stack exchange,提问作者Duncan Groenewald
相关产品推荐
相关产品推荐

