How can I pass a function a parameter

Rather than do this:

Code Block
let skTexture = SKTexture(imageNamed: "slot")
let mySlot = SKSpriteNode(texture: skTexture, color: .clear, size: slotSize)

I would like to grab the texture in the call to create the SKSprite. I know I'm supposed to use closures, yet I am unable to figure out the proper syntax.

Am looking for something like:

Code Block
let mSlot = SKSpriteNode( {texture: SKTexture(imageNamed: "slot") -> (SKTexture)} color: SKColor.clear, size: mySlotSize)


Have tried as many variants as I can think of but never get to the point where I can compile.

If the closure is something that I must predefine, then there's no point in trying this.
Answered by Claude31 in 646810022
It is not alwaysa great idea to try to cram everything in a single line…

Anyway, texture parameter is a SKTexture, not a func nor a closure.

But there is a simple way to achieve your goal:

Code Block
let mySlot = SKSpriteNode(texture: SKTexture(imageNamed: "slot"), color: .clear, size: slotSize)



Accepted Answer
It is not alwaysa great idea to try to cram everything in a single line…

Anyway, texture parameter is a SKTexture, not a func nor a closure.

But there is a simple way to achieve your goal:

Code Block
let mySlot = SKSpriteNode(texture: SKTexture(imageNamed: "slot"), color: .clear, size: slotSize)



If the closure is something that I must predefine, then there's no point in trying this.

Seems the answer of Claud31's is best fit for your purpose.

If you dare use closures, you can predefine a initializer using closure:
Code Block
extension SKSpriteNode {
convenience init(color: UIColor, size: CGSize, texture closure: ()->SKTexture) {
self.init(texture: closure(), color: color, size: size)
}
}

And use it like this:
Code Block
let mSlot = SKSpriteNode(color: SKColor.clear, size: mySlotSize) {
return SKTexture(imageNamed: "slot")
}



Or else, you can invoke a closure instantly at the place, as often found in the initial values of properties:
Code Block
let mSlot = SKSpriteNode(texture: {
return SKTexture(imageNamed: "slot")
}(), color: SKColor.clear, size: mySlotSize)

This make your code more complex than it should be, so may not the thing you want to achieve.

(You can omit the keyword return in both cases, but I made them left there as to clarify they are in closures.)


Maybe we are misunderstanding what you really want to do. If you could clarify that, there might be some other ways.
How can I pass a function a parameter
 
 
Q