Jush KillaB
Jush KillaB

Reputation: 151

Declare passed parameter to var in Swift

I want to create a function that takes 2 parameters and changes their values. Example:

var geometricSprite = SKSpriteNode()
var geoTouched = true
removeTouch(sprite: geometricSprite, bool: getTouched)

func removeTouch(sprite: SKSpriteNode, bool: Bool) {
    sprite.size = 0

    bool = false
    //HERE I GET THE ERROR "Cannot assign to value: 'bool' is a 'let' constant"
}

So again bool = false gives an error because 'bool' is a let constant. I never declared that bool as a let so I do not know how to fix this error.

Upvotes: 0

Views: 2953

Answers (2)

dfrib
dfrib

Reputation: 73176

Unless you specify a function parameter as inout, you may not mutate it.

SKSpriteNode() is of type class, which is a reference type: not marking it inout means you may not mutate the reference itself, whereas you may, however, mutate mutable (accessible) members of the reference type (accessible via the non-mutable reference).

bool, on the other hand, is a value type, which means that you may not mutate it when supplying it as an argument, unless you explicitly mark it as inout.

A hopefully instructive example:

class MyReferenceType {
    var valueTypeMember: Int = 0
}

struct MyValueType {
    var valueTypeMember: Int = 0
}

func mutateMyReferenceAndValueInstances(
    _ ref: MyReferenceType, _ val: inout MyValueType) {
    ref.valueTypeMember = 42
    val.valueTypeMember = 43
}

let ref = MyReferenceType()
var val = MyValueType()

print(ref.valueTypeMember, val.valueTypeMember) // 0 0
mutateMyReferenceAndValueInstances(ref, &val)
print(ref.valueTypeMember, val.valueTypeMember) // 42 43

See e.g. the Language Guide - Functions for details regarding in-out parameters.

Upvotes: 1

David Rönnqvist
David Rönnqvist

Reputation: 56625

Since your are looking to both pass and argument to the function and modify the value that was passed in you need to define that parameter as inout:

func removeTouch(sprite: SKSpriteNode, bool: inout Bool)

That also changes the call site to require a & before the value being passed in

removeTouch(sprite: geometricSprite, bool: &getTouched)

That said, depending on what you are doing with the value that was passed to the function, you are probably better off returning the new value.

func removeTouch(sprite: SKSpriteNode, bool: Bool) -> Bool

Upvotes: 3

Related Questions