0

Let's consider the following code :

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

var AnArrayOfAClass[AClass]()

AnArrayOfAClass[x].AFunction

How can I know in AFunction the value of the index when I call the method AFunction (index is x in the example of call I want to do like in the last line of code just above) ? Is there a way to avoid to pass it as an argument of AFunction ?

Thx

J.

4
  • What is the scope of AnArrayOfAClass? Commented Jan 9, 2015 at 20:40
  • What do you mean by scope (I'm kind of new to swift) ? Commented Jan 9, 2015 at 21:20
  • No worries :) I meant where is it being used in relation to the instance of AClass that is calling it? A function or a closure can "capture" values outside of themselves, but only other values that are in the same "scope" as the function. Sorry, I don't know how to describe it better in a comment, but I don't think it is possible to answer without knowing the scope in which the array and the function are being called... Commented Jan 9, 2015 at 21:30
  • The ‘AnArrayOfAClass‘ array is a global variable declared outside of any specific scope (i.e. not in a function or class) and used at various levels in the code. The 'AFunction' method is called inside the didBeginContact of a SKScene object Commented Jan 9, 2015 at 21:58

1 Answer 1

1

I'm not sure if this will work because I'm still not certain of the scope issue, but this will return the index of the first value in AnArrayOfAClass that is identical to the object calling the function:

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

And I changed everything to camelCase where I thought it was appropriate - no offense intended :)

Sign up to request clarification or add additional context in comments.

2 Comments

And if you make AClass conform to Equatable, you can use find directly without having to do the map first.
Works perfectly, thanks ! I just have now to figure out why and how it works...I'll go back to Swift 101 for that...;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.