在Swift中过滤自定义对象的数组 [英] Filter array of custom objects in Swift

查看:671
本文介绍了在Swift中过滤自定义对象的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试过滤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中过滤自定义对象的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆