gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 06:06:19 26 4
gpt4 key购买 nike

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

    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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com