[英]Filter array of custom objects in Swift
I'm trying to filter an array of custom objects in swift to get back a subset of data that has properties I want to isolate. 我正在尝试在swift中过滤一组自定义对象,以获取具有我想要隔离的属性的数据子集。 My code is as follows.
我的代码如下。
func generateSubset( dataPool : [CustomObject]) -> [CustomObject]? {
let subsetData = dataPool.filter{(includeElement:CustomObject)-> Bool in
return contains(includeElement.position, "TEACHER")
}
return subsetData
}
My custom object is as follows: 我的自定义对象如下:
class CustomObject : {
var position : String?
init(){
position = ""
}
}
However the error Xcode throws me when trying to compile this code is: 但是,在尝试编译此代码时,Xcode抛出的错误是:
Cannot invoke 'filter' with an argument list of type [CustomObject] -> Bool
I'm using Swift 1.2 and can't seem to figure out what I'm doing wrong. 我正在使用Swift 1.2,似乎无法弄清楚我做错了什么。 Any help would be appreciated.
任何帮助,将不胜感激。
In Swift 1.2, filter
is a global function, so you can't say dataPool.filter(...)
. 在Swift 1.2中,
filter
是一个全局函数,所以你不能说dataPool.filter(...)
。 (In Swift 2, this will work.) (在Swift 2中,这将有效。)
Furthermore, contains
can't be used with Strings like that. 此外,
contains
不能与这样的字符串一起使用。 I would recommend using the rangeOfString:
method from NSString: 我建议使用NSString中的
rangeOfString:
方法:
let teachers = filter(dataPool) { // in Swift 2 this would be "dataPool.filter {"
return $0.position!.rangeOfString("TEACHER") != nil
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.