请问有没有一种更简洁的方法或更好的方法来在Swift的循环中编写以下嵌套的for ...?还是用于...以正确的方式填充我的卡?
for cardNumber in 1...3 {
for cardSymbolIdentifier in 1...3 {
for cardColorIdentifier in 1...3 {
for cardShadingIdentifier in 1...3 {
let card = Card(cardNumber: cardNumber, cardSymbolIdentifier: cardSymbolIdentifier, cardColorIdentifier: cardColorIdentifier, cardShadingIdentifier: cardShadingIdentifier)
deckOfCards.append(card)
}
}
}
}
这确实可以完成工作,但是我在文档中找不到有关编写多个嵌套循环的任何内容。
非常感谢, 安迪
答案 0 :(得分:2)
There is absolutely nothing wrong with your for loops. They are excellent, well-written Swift. The only problem with your code is that it forces deckOfCards
to be mutable (var), which may be undesirable. If it is, you could use a map
, but I don't consider this particularly better Swift, just slightly different.
let d = (1...3).flatMap { number in
(1...3).flatMap { symbol in
(1...3).flatMap { color in
(1...3).map { shading in
Card.init(cardNumber: number,
cardSymbolIdentifier: symbol,
cardColorIdentifier: color,
cardShadingIdentifier: shading
)}}}}
I would probably write it this second way, but only for stylistic reasons. Your for loops are absolutely fine.
Note @user28434's comment below. My original version of this had a major bug (it returned the wrong type). I've been writing Swift since the day it was released. I teach Swift. I teach functional programming in Swift. And I screwed it up when writing it on the fly. I would never have made that mistake with a simple for loop. There's a major lesson in there.
答案 1 :(得分:1)
如果您在单个循环中执行此操作,那么它将变得算术复杂
for i in 0..<81 {
deckOfCards.append(
Card(cardNumber: i / 27, cardSymbolIdentifier: i/9 % 3,
cardColorIdentifier: i/3 % 3, cardShadingIdentifier: i % 3)
)
}
或
let deckOfCards = (0..<81).map {
Card(cardNumber: $0 / 27, cardSymbolIdentifier: $0/9 % 3,
cardColorIdentifier: $0/3 % 3, cardShadingIdentifier: $0 % 3)
}
在两个示例中-索引都从0开始,因此您的类init函数应该将索引移很少
或
在传递之前/之后的每个参数中添加+1
答案 2 :(得分:0)
Your code has no optimisation issues at all according to the need but you can make it a little more elegant or swifty (:p)
let values = [1,2,3]
values.forEach { (cardNumber) in
values.forEach { (cardSymbolIdentifier) in
values.forEach { (cardColorIdentifier) in
values.forEach { (cardShadingIdentifier) in
let card = Card(cardNumber: cardNumber, cardSymbolIdentifier: cardSymbolIdentifier, cardColorIdentifier: cardColorIdentifier, cardShadingIdentifier: cardShadingIdentifier)
deckOfCards.append(card)
}
}
}
}