在Swift中过滤自定义对象的数组
我试图在swift中过滤一个自定义对象的数组,以获取具有我想要隔离的属性的数据的子集。 我的代码如下。
func generateSubset( dataPool : [CustomObject]) -> [CustomObject]? { let subsetData = dataPool.filter{(includeElement:CustomObject)-> Bool in return contains(includeElement.position, "TEACHER") } return subsetData }
我的自定义对象如下所示:
class CustomObject : { var position : String? init(){ position = "" } }
但是,当试图编译这段代码时,Xcode会抛出错误:
Cannot invoke 'filter' with an argument list of type [CustomObject] -> Bool
我正在使用Swift 1.2,似乎无法弄清楚我做错了什么。 任何帮助,将不胜感激。
在Swift 1.2中, filter
是一个全局函数,所以你不能说dataPool.filter(...)
。 (在Swift 2中,这将起作用。)
此外, contains
不能用于像这样的string。 我build议使用NSString中的rangeOfString:
方法:
let teachers = filter(dataPool) { // in Swift 2 this would be "dataPool.filter {" return $0.position!.rangeOfString("TEACHER") != nil }