问题描述
我在数组中有UserDetails结构对象。我想从数组中过滤掉对象。但是在Swift数组中没有filteredArrayUsingPredicate选项。
I have "UserDetails" struct objects in array..I want to filter the objects from array. But there is no option for "filteredArrayUsingPredicate" in Swift array.
我的数组创建
var arrayOfUsers:UserDetails[] = UserDetails[]()
我的userdetails代码是
my userdetails code is
struct UserDetails{
var userName:String
var userID:String
var userAge:String
func userDescription()->String{
return "name " + userName + "age " + userID
}
}
我创建对象的代码
for a in 1...1000{
var user:UserDetails = UserDetails(userName: "name", userID: String(a), userAge: "22")
arrayOfUsers.append(user)
}
现在我要过滤 arrayOfUsers
其中一个有userID1。
Now I want to filter arrayOfUsers
which one has userID "1".
推荐答案
Swift数组有一个 .filter
关闭的方法 - 这样做:
Swift arrays have a .filter
method that takes a closure -- this will do it:
let filteredArray = arrayOfUsers.filter() { $0.userID == "1" }
可以通过多种方式简化闭包。闭包的完整声明看起来更像是:
Closures can be simplified in a variety of ways. The full declaration of the closure would look more like this:
var filteredArray = arrayOfUsers.filter( { (user: UserDetails) -> Bool in
return user.userID == "1"
})
两者之间的区别在于第一个是使用尾随闭包语法,简写参数名称,类型推断和隐式返回。您可以阅读。
The difference between the two is that the first is using trailing closure syntax, shorthand argument names, type inference, and implicit return. You can read more about closures in Apple's Swift documentation.
这篇关于swift Array中不存在filteredArrayUsingPredicate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!