Mahmud Ahmad
Mahmud Ahmad

Reputation: 171

looking at Apple's "Adventure Game" tutorial what does "in" mean?

While looking at the source code for the tutorial adventure game using SpriteKit by Apple, I kept seeing variables being declared, and after they are declared there are open brackets, and the word "in".

This is the code I am using:

 let rightThumbstickHandler: GCControllerDirectionPadValueChangedHandler = { dpad, x, y in
        let length = hypotf(x, y)
        if length <= 0.5 {
            player.heroFaceLocation = nil
            return
        }

Like that, the "dpad, x, y in". Does anyone know what those are/what they are used for?

Upvotes: 2

Views: 476

Answers (2)

eric bob
eric bob

Reputation: 235

This is a closure. it is basically structured like a function.

a function is

func ( dpad:Cgpoitn,x:cgfloat, y:cgfloat)->(void){
//code 
}

a closure is just structured differently.

{dpad,x,y in 
//the code
}

go to a 34 min 00 and watch the next 2 minutes and closures are explained well https://www.youtube.com/watch?v=QLJtT7eSykg -- paul hegarty : developing iOS apps with swift available on iTunes U - he is awesome

Upvotes: 1

Sebastian
Sebastian

Reputation: 8164

This is a closure definition which captures three variables whose parameters are dpad, x and y. The in declares the actual beginning of the code which the closure executes. The values of the variables are provided by the caller.

Update: the in helps to mark the beginning of the code, i.e. suppose you have the following optional closure variable:

var foo : (Array<Int> -> Int)?

Now, you want to actually define this in your code and you want to achieve (pseudo-code):

foo = { for every int in array -> sum }

The question is, how do you access the array? And this is, when pattern matching jumps in, e.g.

foo = { numbers [...] }

Here, the array will be assigned to an immutable variable named numbers. After this you could write your code directly, but how do you want to distinct between variable assignments from the caller via pattern matching and local variables? And this is, when in comes into play, e.g. you would write

foo = { numbers in return numbers.reduce(0, { $0 + $1 }) }

Now, it is clear, that everything after in will be used inside the closure for computation. Furthermore, by having a look at the initial definition of the closure variable, you will also know, what type numbers will be.

For the sake of completeness, you can now call this by

let x = foo?([1, 2, 3]) // x = 6

Upvotes: 6

Related Questions