在 Swift 中对数组进行冒泡排序,交换时出现编译器错误 [英] Bubble sorting an array in Swift, compiler error on swap
问题描述
我为纸牌游戏编写了一个非常简单的冒泡排序.它接受一组卡片"对象,每个对象都有一个顺序"属性,该属性指示要针对相关游戏进行排序的值.
I wrote a really simple bubble sort for a card game. It takes an array of "Card" objects, each of which has a an "order" attribute which indicates the value to be sorted against for the game in question.
以下代码在 Swift Beta 1 和 Beta 6 之间的一段时间内停止编译,我不确定为什么.
The following code stopped compiling some time between Swift Beta 1 and Beta 6, and I'm not exactly sure why.
///Sort the cards array by order
func sortCards(cards: Array<Card>) -> Array<Card> {
var sorted = false
while sorted == false {
sorted = true
for i in 0...cards.count - 2 {
if cards[i].order > cards[i+1].order {
sorted = false
var first = cards[i]
var second = cards[i + 1]
cards[i] = second //ERROR
cards[i + 1] = first //ERROR
}
}
}
return cards
}
发生交换的那几行带有一个非常神秘的消息:
The lines where the swap occurs bombs out with a very cryptic message:
@!value $T5 与 'Card' 不同
发生了什么变化,我在这里做错了什么?
What changed, and what am I doing wrong here?
额外问题:我应该如何理解错误消息?
Bonus question: How am I supposed to understand the error message?
推荐答案
函数参数默认为常量(就像用 let
声明一样).如果要修改函数内部的参数,必须将其声明为变量:
Function parameters are by default constant (as if declared with let
).
If you want to modify the parameter inside your function, you have to declare it as a variable:
func sortCards(var cards: Array<Card>) -> Array<Card> { ...
注意只修改了局部参数cards
,而不是传入的数组函数的参数(这似乎是您的意图,因为函数返回一个新数组.
Note that only the local parameter cards
is modified, not the array passed as
an argument to the function (which seems to be your intention because the function
returns a new array).
这篇关于在 Swift 中对数组进行冒泡排序,交换时出现编译器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!