Filter an array of custom objects in Swift

I am trying to filter out an array of user objects in swift to get a subset of data that has properties that I want to highlight. 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 Xcode error causes me to try to compile this code:

 Cannot invoke 'filter' with an argument list of type [CustomObject] -> Bool 

I am using Swift 1.2 and I can’t understand what I am doing wrong. Any help would be greatly appreciated.

+4
source share
1 answer

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

In addition, contains cannot be used with such strings. 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 } 
+5
source

All Articles