在Swift中过滤自定义对象的数组

编程入门 行业动态 更新时间:2024-10-06 06:46:47
本文介绍了在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中过滤自定义对象的数组

本文发布于:2023-11-26 19:08:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634824.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   数组   对象   Swift

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!