ios - 如何查询一个对象是否是数组的成员?

标签 ios arrays swift

我正在设计一个空当接龙纸牌游戏,我的纸牌(模型)和cardViews( View )都在代表纸牌列的数组中 - 然后整个棋盘是一个列数组:

//in the model: 
typealias Card = DeckBuilder.Card
typealias Column = [Card]
var board = [Column](repeating: [], count: 8)
//in the view controller:
var boardForView = [[PlayingCardView]](repeatElement([PlayingCardView](), count: 8))

当用户点击cardView时,我希望 Controller 获取所选cardView的列和行(其中列是板中的哪一列,行是列中的哪张卡),然后在模型中的相应位置。

我已经设置了点击手势识别器,并从中提取了cardView:

    func selectCard(_ sender: UITapGestureRecognizer) {
    if let selectedCard = sender.view as? PlayingCardView {
        print("card selected: \(selectedCard.cardDescription?.string)")
    }
}

所以问题是:cardView 是否有一个属性是它在列数组中的位置,然后该列的属性是该列在 boardForView 数组中的位置吗?

最佳答案

我明白了!我想到的一种方法是迭代棋盘每一列中的每张卡,并检查它是否==我当前的卡。看起来太笨重了。但后来我发现了 array.index(of: element) 并且我的日子得救了!我确实必须遍历板上的每一列,但它仍然更优雅:

    func selectCard(_ sender: UITapGestureRecognizer) {
    if let currentCard = sender.view as? PlayingCardView {
        for column in 1...boardForView.count {
            if let row = boardForView[column - 1].index(of: currentCard) {
                print("card selected: \(currentCard.cardDescription!.string) in row \(row+1) of column \(column)")
                selectedCard = freeCellGame.board[column - 1][row]
                print("card selected from model: \(selectedCard!.description)")
            }
        }
    }
}

关于ios - 如何查询一个对象是否是数组的成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41649406/

相关文章:

ios - AWS Batch 请求按值数组过滤的多项

objective-c - 在 UIWebView 可以显示之前注释掉 HTML 中的字符串

ios - 获取 UITextView 中特定字符串每次出现的 Y 坐标以进行行编号

ios - Swift NSMutableDictionary 删除对象

ios - 为什么在设置 NSManagedObject 的属性时抛出异常?

ios - NSPredicate 在 Objective C 中查找多个单词

php - 将 MySQL 结果填充到网格中

ios - Swift 2.1 破坏了 ZCarousel;字符串数组

java - 知道何时结束冒泡排序中的循环

swift - 如何快速格式化固定长度的字符串