4

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.

1 Answer 1

5

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.