我正在尝试过滤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. 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 }我的自定义对象如下:
class CustomObject : { var position : String? init(){ position = "" } }但是,在尝试编译此代码时,Xcode抛出的错误是:
However the error Xcode throws me when trying to compile this code is:
Cannot invoke 'filter' with an argument list of type [CustomObject] -> Bool我正在使用Swift 1.2,似乎无法弄清楚我做错了什么。任何帮助,将不胜感激。
I'm using Swift 1.2 and can't seem to figure out what I'm doing wrong. Any help would be appreciated.
推荐答案在Swift 1.2中,过滤器是一个全局函数,所以你不能说 dataPool.filter(...)。 (在Swift 2中,这将有效。)
In Swift 1.2, filter is a global function, so you can't say dataPool.filter(...). (In Swift 2, this will work.)
此外,包含不能与这样的字符串一起使用。我建议使用NSString中的 rangeOfString:方法:
Furthermore, contains can't be used with Strings like that. I would recommend using the rangeOfString: method from NSString:
let teachers = filter(dataPool) { // in Swift 2 this would be "dataPool.filter {" return $0.position!.rangeOfString("TEACHER") != nil }更多推荐
在Swift中过滤自定义对象的数组
发布评论