如何解决“参数类型'CustomStruct'不符合预期类型'序列'”

时间:2018-02-10 20:47:13

标签: swift xcode

我试图使用下面的代码 shuffle 一个由名为Card的简单自定义结构组成的数组,我在cards.remove(at: randomIndex)收到错误:

Error: Argument type 'Card' does not conform to expected type 'Sequence'

以下是代码:

var cards = [Card]()  // declare the array
var shuffledCards = [Card]()
for _ in cards.indices {
    let randomIndex = Int(arc4random_uniform(UInt32(cards.count)))
    shuffledCards += cards.remove(at: randomIndex)  // error appears here
}
cards = shuffledCards

奇怪的是,作为对比,类似的设计适用于Array<String>

var emojiChoices = ["", "", "", "", "", "", "", "", ""]
let randomIndex = Int(arc4random_uniform(UInt32(emojiChoices.count)))
emoji[card.identifier] = emojiChoices.remove(at: randomIndex)

我应该添加Card的定义吗?如果是这样,我应该添加什么?谢谢!

1 个答案:

答案 0 :(得分:3)

中的+=运算符
shuffledCards += cards.remove(at: randomIndex)

需要一个序列元素,它们应该附加到 shuffledCards数组(例如另一个数组)。要附加单个元素,请使用

shuffledCards.append(cards.remove(at: randomIndex))