【问题标题】:Swift: filter an array of Element1 [(String, Bool)] to return AND convert to an array of Element2 [String]?Swift:过滤 Element1 [(String, Bool)] 的数组以返回并转换为 Element2 [String] 的数组?
【发布时间】: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


【解决方案1】:

使用compactMap()怎么样?

在某种意义上,可以理解为filter()(你已经在使用)+map()(也就是第一个解决方案中的循环for existingFriend in newArray

let userArrayForTableView = friendArray.compactMap({ (existingFriend) in 
    if excludeUsers.contains($0.userID) {
        return nil
    } else {
        return existingFriend.id
    }
})

简而言之:

let userArrayForTableView = friendArray.compactMap({ excludeUsers.contains($0.userID) ? nil : $0.userID })

【讨论】:

  • 谢谢!这比我要找的还要好哈哈。完美的。一个简单的问题:如果它返回 nil 的值,数组是 [id1, nil, id3] .. 还是 [id1, id3]?我希望是后者,因为我将在 tableview 中使用结果数组并且不想要 nil 单元格。
  • 如果闭包返回 nil,那么它不会将值添加到数组中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-14
  • 2011-04-06
  • 2015-04-09
  • 1970-01-01
  • 2018-05-08
相关资源
最近更新 更多