swift - for if in swift 更优雅的代码

标签 swift if-statement for-loop

我得到了一个简单的代码,它可以工作,我正在用老式的方式编程,我相信有一种更优雅的方式可以快速地做到这一点。这是代码:

    var cardsInCompartment1:Int = 0
    var cardsInCompartment2:Int = 0
    for card in cards{
        if card.compartment == 1{
            cardsInCompartment1 += 1
            print(cardsInCompartment1)
        }
        if card.compartment == 2{
            cardsInCompartment2 += 1
            print(cardsInCompartment2)
        }
    }

我基本上是在不同的隔间里拿到了卡片,现在我想数一数每个隔间里有多少张卡片。

最佳答案

如何使用 filter 来选择您想要的卡片?然后你可以计算它们:

let cardsInCompartment1 = cards.filter { $0.compartment == 1 }.count
let cardsInCompartment2 = cards.filter { $0.compartment == 2 }.count

如果你有一堆隔间,你可以将计数存储在字典中:

var compartmentCounts = [Int:Int]()

cards.forEach {
    compartmentCounts[$0.compartment] = (compartmentCounts[$0.compartment] ?? 0) + 1
}

在这种情况下,键是隔间#,值是卡数。类似于 [1: 32, 2: 42] 如果每个隔间中有 32 和 42 张卡片。

关于swift - for if in swift 更优雅的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36467089/

相关文章:

java - 在十二生肖确定器中接收有效输入的无效 I/O

java - 使用 for 循环从任意大小的列表中获取多个 WebElement

javascript - 在 forEach 循环中访问数据

python - 如何将 forloop.counter 连接到我的 django 模板中的字符串

swift - SceneKit - 由 childNode 查找导致的无限内存增长

swift - 是否可以在 SwiftUI 中突出显示鼠标悬停时的行

ios - SKTileMap 从 GKNoiseMap 获取值

json - 从 Firebase Swift 读取两个数据模型

具有多个值的 PHP if 语句

python - 无法让我的 else 语句在 while 循环中打印