【问题标题】:Swift Array of class : how to find index in a method of the classSwift Array of class:如何在类的方法中查找索引
【发布时间】:2015-03-08 03:05:00
【问题描述】:

让我们考虑以下代码:

Class AClass : SKNode
{
    func AFunction ()
    {
        // Some code
    }
}

var AnArrayOfAClass[AClass]()

AnArrayOfAClass[x].AFunction

当我调用方法 AFunction 时,我如何在 AFunction 中知道索引的值(在我想要执行的调用示例中,索引是 x,就像上面最后一行代码一样)?有没有办法避免将其作为 AFunction 的参数传递?

谢谢

J.

【问题讨论】:

  • AnArrayOfAClass的范围是什么?
  • 范围是什么意思(我对 swift 有点陌生)?
  • 不用担心 :) 我的意思是它在哪里被用于调用它的 AClass 实例?函数或闭包可以“捕获”自身之外的值,但只能捕获与函数处于相同“范围”内的其他值。抱歉,我不知道如何在评论中更好地描述它,但我认为在不知道数组和函数被调用的范围的情况下无法回答......
  • “AnArrayOfAClass”数组是在任何特定范围之外(即不在函数或类中)声明的全局变量,并在代码的各个级别使用。 'AFunction' 方法在 SKScene 对象的 didBeginContact 内部调用

标签: arrays class swift methods indexing


【解决方案1】:

我不确定这是否可行,因为我仍然不确定范围问题,但这将返回AnArrayOfAClass 中与调用函数的对象相同的第一个值的索引:

class AClass {
    func aFunction() {

        //  This maps AnArrayOfAClass to an array of Bool values depending
        //  on whether or not the value at the index === the object calling the function
        //  and then returns the index of the first true that it encounters:

        if let index = find(anArrayOfAClass.map({ $0 === self }), true) {
            println(index)
        }
    }
}

var anArrayOfAClass = [AClass]()

let aClass = AClass()

anArrayOfAClass += [aClass]

anArrayOfAClass[0].aFunction()   //  If everything worked, this should print "0", 
                                 //  which is the correct index of aClass

我将所有内容都更改为我认为合适的 camelCase - 无意冒犯:)

【讨论】:

  • 而且如果你让AClass符合Equatable,你可以直接使用find,而不必先做map。
  • 完美运行,谢谢!我现在只需要弄清楚它为什么以及如何工作...我将为此返回 Swift 101...;-)
猜你喜欢
  • 1970-01-01
  • 2019-07-04
  • 2020-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多