Swift 2.0 filtering array of custom objects - Cann

2019-06-04 07:17发布

问题:

trying to filter an array of custom object type ParseEmployee which inherits from NSObject.

Any ideas what could be causing this error?

回答1:

Consider the following example:

struct MyEmployee {
    var employeeId : Int
    var employeeName : String
    var employeeAge : Int
    var employeeGender : String

    init(_ id: Int, _ name: String, _ age: Int, _ gender: String) {
        employeeId = id
        employeeName = name
        employeeAge = age
        employeeGender = gender
    }
}

var arrayOfEmployees : [MyEmployee] = [MyEmployee(1, "John", 28, "Male"), MyEmployee(2, "Sarah", 35, "Female"), MyEmployee(3, "Christine", 24, "Female")]

var filtered = arrayOfEmployees.filter {employee in employee.employeeAge < 30 }
print(filtered) // Employee objects John and Christine

The closure following .filter suffix to your array must be of return type Bool ("element-type-of-array" -> Bool). You either explicitly add a return or simply make sure the statement following employee in is one that evaluates to type Bool (e.g., employee.employeeAge < 30, which returns true or false).

Note that you can treat the closure as any anonymous closure type, not necessarily using a single-line statement. E.g.:

var anotherFiltered = arrayOfEmployees.filter{
    employee in
    return employee.employeeAge < 30 && employee.employeeGender == "Female" }
print(anotherFiltered) // Employee object Christine


回答2:

You should be able to run as the following:

filtered = arrayOfEmployees.filter { // filter them here }

$0 will be the member of the array and you just have to make sure the braces return a true or false Bool, you do not need to do (employee) -> Bool in here.

If you wanted employee just do the following:

filtered = arrayOfEmployees.filter { employee in // filter here }


回答3:

Your filter closure has to return a Bool.

So something like.

filtered = arrayOfEmployees.filter { return true }

Now that's not useful because nothing is filtered but it fixes your error. Let's say your ParseEmployee has a property isManager:Bool. Then you could do something like.

filtered = arrayOfEmployees.filter { $0.isManager }


回答4:

My problem was that I had copied and pasted the "filtered" array from another class and didn't change it to the appropriate class type that was being filtered. I changed the filtered array to the correct class and this resolved the error.