Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

ios - 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. 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:

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. Any help would be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In Swift 1.2, filter is a global function, so you can't say dataPool.filter(...). (In Swift 2, this will work.)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...