ios - 索引(其中 :) method in swift is producing the wrong index

标签 ios arrays swift closures indexoutofrangeexception

我收到了数组索引超出范围的错误。我有两个数组 cardsCurrentlyInPlaycurrentCardsSelected。这个游戏中的每张卡都有一个唯一的 ID。我试图在 cardsCurrentlyInPlay 中找到卡的索引,其 cardIDcurrentCardsSelected 中卡的 cardID 相匹配>。我通过使用采用闭包的 index(where:) 方法来执行此操作。我的闭包只是检查 ID 是否匹配,它们显然匹配,因为我正在使用 ! 来解包它们并且应用程序不会在那里崩溃。似乎 index(where:) 方法返回了错误的索引。我已经看了好几个小时了,但我不明白发生了什么。

代码如下:

    let indexOfFirstCard = cardsCurrentlyInPlay.index(where: ({($0?.cardID == currentCardsSelected[0].cardID)}))!
    let indexOfSecondCard = cardsCurrentlyInPlay.index(where: ({($0?.cardID == currentCardsSelected[1].cardID)}))!
    let indexOfThirdCard = cardsCurrentlyInPlay.index(where: ({($0?.cardID == currentCardsSelected[2].cardID)}))!

    if deck.isEmpty && selectedCardsMakeASet() {

        /* Remove the old cards */
        cardsCurrentlyInPlay.remove(at: indexOfFirstCard)
        cardsCurrentlyInPlay.remove(at: indexOfSecondCard)
        cardsCurrentlyInPlay.remove(at: indexOfThirdCard) // where code is blowing up

        currentCardsSelected.removeAll()

        /* Return indicies of cards to clear from the UI */
        return .deckIsEmpty(indexOfFirstCard, indexOfSecondCard, indexOfThirdCard)

    }

Here is where I am getting an index out of range error

Each card has a unique ID, so my second card in <code>currentCardsSelected</code> has an ID of 47. I base the closure that I pass into the index function (see first picture) based off this ID. Basically, find the index of the card in <code>cardsCurrentlyInPlay</code> whose cardID matches the cardID of the card in <code>currentCardsSelected</code>. Either I have completely lost my mind or the index(where:) method is returning the wrong index.

最佳答案

你得到的索引在你得到它时是正确的,但是当你移除其他卡片时它变得是错误的。考虑:

var a = ["x", "y", "z"]
let indexOfX = a.index(of: "x")!  // returns 0
let indexOfZ = a.index(of: "z")!  // returns 2
a.remove(at: indexOfX)  // removes "x"; now a = ["y", "z"]
a.remove(at: indexOfZ)  // index 2 is now out of bounds

您可以交替调用 index(of:)remove(at:),但更好的方法是一次删除所有三张卡片,像这样:

let selectedCardIDs = currentCardsSelected.map { $0.cardID }
cardsCurrentlyInPlay = cardsCurrentlyInPlay.filter { card in
    !selectedCardIDs.contains(card.cardID)
}

请注意,这具有避免强制展开的额外好处,这是更合理逻辑的标志。

关于ios - 索引(其中 :) method in swift is producing the wrong index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49972754/

相关文章:

Swift,FIrebase - 无法通过 removeAllObservers 删除观察者

ios - UISegmentedControl 未接收到触摸

objective-c - 在非 ARC 项目中包含 ARC header

python - 计算交集时避免 numpy 循环

c++ - 如何在 C++ 中将数组右移?

ios - AWS Cognito 用户池 - "Value null at ' userName' 未能满足约束 : Member must not be null"- iOS

ios - 如何使我的页面 View Controller 不至于无穷无尽?

ios - 以编程方式添加到 View Controller 的 UITableView 不会填充

Javascript:Object.setup() 不是函数

ios - 访问导航栏高度和状态栏高度