2016-04-07 178 views
1

我得到了一个简单的代码,它的工作原理和我正在编程和老式的方式,我相信有一个更加优雅的方式做到这一点很快。这里是代码:更优雅的代码为如果在迅速

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

我基本上有卡在不同的车厢,现在我想要计算每个车厢里有多少张牌。

回答

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]

+0

这里的主要问题是,您现在在列表中迭代两次。 –

+0

@ magni-我不认为这是一个大问题,除非有明显的性能问题。编译器完全有可能消除大部分的低效率......并且对于少量的卡片来说,这并不重要。对我来说,代码可读性是第一位的。 –

+0

@ magni-我更新了一个解决方案,它在一次迭代中完成。 –

1

试试这个:

var cardsInCompartment1:Int = 0 
var cardsInCompartment2:Int = 0 
for card in cards { 
    (card.compartment == 1) ? (cardsInCompartment1 += 1) : (cardsInCompartment2 += 1) 
} 
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: 
} 
0

或者,使用数组来保持你的罪状:

var counts = [ 0, 0, 0 ] // create an array of integers, where the Ints in the array represent the count of cards in each compartment 
cards.forEach { counts[ $0.compartment ] += 1 } // for each card, increment the count in array corresponding to the compartment of the card. (if card.compartment == 1, increment counts[1], and so on 

print("cards in compartment 1 \(counts[1])") 
print("cards in compartment 2 \(counts[2])") 

(这是假设你只有车厢是整数1和2)

+0

这真是太棒了,但是让我想起了我曾经一次又一次地看到的C比赛中的编程,这将对谁能够为特定任务创建最小的最快代码提出挑战。结果通常很精彩,而且完全隐晦,因为很难理解它在做什么,最终需要在编码上达到平衡。没有不尊重nielsbot意图! 12.8k的声望为自己说明了自己的能力,并做了这两行守护进程。 – user3069232

+0

我会添加一些评论:) – nielsbot

+0

另外,我认为@Aaron Brager的解决方案在上面的空间更加一般。 – nielsbot

1

我想你应该保存cardsInCompartment为数组:

var cardsInCompartment = [0, 0] // you can add more to this array 

然后你可以循环通过cards并将值添加到数组元素中:

for card in cards { 
    cardsInCompartment[card.compartment - 1] += 1 
    print(cardsInCompartment[card.compartment - 1]) 
} 
+0

这将打印每个卡_cards_ – nielsbot

+0

@nielsbot所以什么?从给定的情况来看,我认为他打算打印所有的卡片。 – Sweeper

+0

好。这就是原来的做法。似乎是无意的。 – nielsbot

0

我喜欢Aaron Brager的想法,它将数值计算为字典。我正在使用reduce来消除“循环”之外的可变字典(更多功能)

let d = cards.reduce([:]) { (d, card) -> [Int:Int] in 
    var d = d 
    let s = d[card.compartment] ?? 0 
    d[card.compartment] = s + 1 
    return d 
}