gpt4 book ai didi

arrays - Swift 2.0 过滤自定义对象数组 - 无法使用列表类型的参数调用 'filter'

转载 作者:行者123 更新时间:2023-11-28 06:51:56 25 4
gpt4 key购买 nike

enter image description here

尝试过滤继承自 NSObject 的自定义对象类型 ParseEmployee 的数组。

知道是什么导致了这个错误吗?

最佳答案

考虑以下示例:

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

.filter之后关闭数组的后缀必须是返回类型 Bool ("element-type-of-array" -> Bool)。您要么显式添加 return或者简单地确保 employee in 之后的声明是一个评估类型 Bool (例如 employee.employeeAge < 30 ,返回 truefalse )。

请注意,您可以将闭包视为任何匿名闭包类型,不一定使用单行语句。例如:

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

关于arrays - Swift 2.0 过滤自定义对象数组 - 无法使用列表类型的参数调用 'filter',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34618269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com