我是 Swift 新手...
我循环浏览一手牌(下面未显示),并将每张牌与之前确定的最佳选项进行比较。如果它有更好的值,则用这张卡和适当的值替换结构变量“bestOption”(penaltyValue是任意的,可以是-5、-1、9、199,对于本题来说无关紧要)。
因此,对于我手中的每张卡,我都将其与该卡调用“compareReplaceBestOption”。
bestOption 变量是一个结构体,最初为空(无值),因此将填充第一张卡片和值。对于下面的每张卡,我都会将卡与 bestOption 变量中的值进行比较(并可能替换)(这将具有一定的值(value))。
这段代码很丑陋,可能有几个原因(所有建议都值得赞赏),但真正让我震惊的是对变量 bestOption (一个结构)的双重赋值。
问题:是否有一种更优雅的解决方案,因此只有一个分配(我可以创建一个执行分配的小函数,但最终我会遇到概念上相同的问题)
这句话重复两次会让人受伤......
bestOption = ( card
, newPenaltyValue
)
(辅助信息:g.cardStack[0]是上一轮打出的牌,面朝上在堆栈上。手牌与这张牌进行比较)
//Find penalty and card for card in hand with lowest possible penalty
//AND without using the bonusChip
var bestOption: (card: Card!, penaltyValue: Int!)?
func compareReplaceBestOption(card: Card) {
let newPenaltyValue = card.nr - g.cardStack[0].nr - 1
if bestOption == nil { bestOption = ( card
, newPenaltyValue
)
} else
{ if ( newPenaltyValue < bestOption!.penaltyValue ) {
bestOption = ( card
, newPenaltyValue
)
}
}
}
最佳答案
针对 Swift 3.0 进行了更新:
if let best = bestOption, best.penaltyValue > newPenaltyValue {
best = (car, newPenaltyValue)
}
(实际上只是丢失了 where
子句。)
旧的更新答案:
<小时/>After revisiting this answer, I think we can improve to make this more Swifty:
if let best = bestOption where best.penaltyValue > newPenaltyValue { best = (car, newPenaltyValue) }
We use the optional unwrapping feature and the
where
-clause to provide some addition cases to check against (even using the now-unwrappedbest
). Much easier to read and we drop that pesky!
.
原答案:
How about:
if bestOption == nil || newPenaltyValue < bestOption!.penaltyValue { bestOption = (car, newPenaltyValue) }
关于swift - 可以删除重复的代码,有更优雅的解决方案吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31408946/