如果在swift中更优雅的代码

时间:2016-04-07 05:03:15

标签: swift if-statement for-loop

我得到了一个简单的代码,该代码可以工作,我正在编程并采用老式的方式,我相信在swift中有更优雅的方式。这是代码:

    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)
        }
    }

我基本上把卡片放在不同的隔间里,现在我想计算每个隔间里有多少张卡片。

6 个答案:

答案 0 :(得分:3)

如何使用filter选择您想要的卡片?然后你可以count他们:

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
}

在这种情况下,密钥将是隔间#,值将是卡计数。如果每个相应的隔间中有32张和42张卡,则为[1: 32, 2: 42]之类的东西。

答案 1 :(得分:1)

试试这个:

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

答案 2 :(得分:1)

我认为你应该将<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 存储为数组:

cardsInCompartment

然后你可以循环遍历var cardsInCompartment = [0, 0] // you can add more to this array 并将值添加到数组元素:

cards

答案 3 :(得分:0)

switch语句怎么样?像这样的东西?

var card:Int = 1
var CardsInCompartment:Int = 0
switch (card) {
case 1:
  CardsInCompartment += 1
  print("CardsInCompartment \(CardsInCompartment)")
case 2:
  CardsInCompartment += 2
  print("CardsInCompartment \(CardsInCompartment)")
default:
}

答案 4 :(得分:0)

或者,使用数组来保持计数:

<template name="radio">
  <div class="radio-group">
    {{#each value}}
      <label class="radio-item">
        <input class="radio-icon" type="radio" name={{group}} checked={{value}} value={{name}}>
        <span class="radio-label">{{caption}}</span>
      </label>
    {{/each}}
  </div>
</template>

(这假设您的唯一隔间是整数1和2)

答案 5 :(得分:0)

我喜欢Aaron Brager的想法,将价值计入字典。我正在使用reduce来消除&#39;循环之外的可变字典。 (更多功能)

 bindEvents : function(){
        this.$elSubmit = $('.permissions-submit');
        this.$elSubmitButton = this.$elSubmit.find('button');
        console.log('submit',this.$elSubmitButton);
        this.$elSubmitButton.on('click',this.permissionsSubmit.bind(this));
    }