【发布时间】:2020-06-09 13:21:51
【问题描述】:
我有一个 [(userID: String,friendBool: Bool)] 数组,我想过滤并转换为 userID 唯一的 [String] 数组(删除friendBool 并因此更改元素)。 Swift 中是否有执行此操作的函数?
目前,我正在对数组进行过滤,然后在过滤后的数组 [(userID: String,friendBool: Bool)] 上使用 for 循环将其转换为 [String] 数组。有没有更好的方法来做到这一点?
当前代码:
let friendArray = [(userID: String, friendBool: Bool)]()
let excludeUsers = [String]()
//Updates with user actions
var userArrayForTableView = [String]()
//Filter friendArray
let newArray = friendArray.filter { (existingFriend) -> Bool in
return !excludeUsers.contains(existingFriend.userID)
}
//Convert array fro [(userID: String, friendBool: Bool)] to [String]
for existingFriend in newArray {
userArrayForTableView.append(existingFriend.userID)
}
我正在尝试做的事情:
//Loaded on ViewDidLoad
let friendArray = [(userID: String, friendBool: Bool)]()
let excludeUsers = [String]()
//Updates with user actions
var userArrayForTableView = [String]()
//Filter friendArray
/*
Below fitler returns an array of [(userID: String, friendBool: Bool)]...
but I want a filter to return an array of [String] for just userIDs
*/
let newArray = friendArray.filter { (existingFriend) -> Bool in
return !excludeUsers.contains(existingFriend.userID)
}
//ERROR HERE because 'newArray' is not [String]
userArrayForTableView.append(contentsOf: newArray)
【问题讨论】:
-
如果我理解正确(我可能已经颠倒了输出条件):
let result = friendArray.compactMap({ excludeUsers.contains($0.userID) ? nil : $0.userID })? -
你应该真的创建一个
User结构。元组旨在以一种快速便捷的方式从函数中返回一些值。它们比结构/类更受限制(它们没有名称,它们不符合协议,它们不能有方法、计算属性、在它们上定义的下标),并且它们不保护它们内脏。在当前的设置下,没有什么能阻止您创建像(userID: "Obviously not a real user ID", friendBool: true)这样的值
标签: arrays swift for-loop filter