filteredArrayUsingPredicate在swift数组中不存在
我有arrays中的“UserDetails”结构对象..我想过滤arrays中的对象。 但是在Swift数组中没有“filteredArrayUsingPredicate”选项。
我的数组创build
var arrayOfUsers:UserDetails[] = UserDetails[]()
我的用户代码是
struct UserDetails{ var userName:String var userID:String var userAge:String func userDescription()->String{ return "name " + userName + "age " + userID } }
我的代码来创build对象
for a in 1...1000{ var user:UserDetails = UserDetails(userName: "name", userID: String(a), userAge: "22") arrayOfUsers.append(user) }
现在我想过滤arrayOfUsers
哪一个有userID“1”。
Swift数组有一个.filter
方法需要closures – 这将做到这一点:
let filteredArray = arrayOfUsers.filter() { $0.userID == "1" }
可以用各种方法简化闭合。 closures的完整声明看起来更像这样:
var filteredArray = arrayOfUsers.filter( { (user: UserDetails) -> Bool in return user.userID == "1" })
两者的区别在于第一个是使用尾随闭包语法,速记参数名称,types推断和隐式返回。 您可以在Apple的Swift文档中阅读更多关于闭包的信息 。
你也可以使用NSPredicate
var customerNameDict = ["firstName":"karthi","LastName":"alagu","MiddleName":"prabhu"]; var clientNameDict = ["firstName":"Selva","LastName":"kumar","MiddleName":"m"]; var employeeNameDict = ["firstName":"karthi","LastName":"prabhu","MiddleName":"kp"]; var attributeValue = "karthi"; var arrNames:Array = [customerNameDict,clientNameDict,employeeNameDict]; var namePredicate = NSPredicate(format: "firstName like %@",attributeValue); let filteredArray = arrNames.filter { namePredicate.evaluateWithObject($0) }; println("names = ,\(filteredArray)");
//结构过滤
struct myStruct { var userid:String; var details:String; init() { userid = "default value"; details = "default"; } }; var f1 = myStruct(); f1.userid = "1"; f1.details = "Good boy"; var f2 = myStruct(); f2.userid = "2"; f2.details = "Bad boy"; var arrNames1:Array = [f1,f2]; let filteredArrayStruct = arrNames1.filter( { (user: myStruct) -> Bool in return user.userid == "1" }) println("filter array count = \(filteredArrayStruct.count)"); for filteredValues in filteredArrayStruct { println("filteredArrayStruct = ,\(filteredValues.details)"); }
如果你正在过滤字典,你可以这样做。
var visitors = [["age" : 22], ["age" : 41], ["age" : 23], ["age" : 30]] var filteredVisitors = visitors.filter({ $0["age"] < 30 }) println(filteredVisitors) //[["age" : 22], ["age" : 23]]
那么这同样适用于你要过滤它的属性的结构
struct Person { var age : Int? init(age: Int) { self.age = age } } var eventAttendees = [Person(age: 22), Person(age: 41), Person(age: 23), Person(age: 30)] var filteredAttendees = eventAttendees.filter({ $0.age < 30 })
你可以参考这篇文章的更多信息。 筛选Swift字典或对象属性的数组