0

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.

3
  • Are you just trying to assign to it or are you also looking to change the value of getTouched that was passed to it? Commented Nov 7, 2017 at 17:31
  • I am trying to change the value to "false". But the error appears! Commented Nov 7, 2017 at 17:58
  • You don't need to have declared it. In the Swift manual, "Functions": "Function parameters are constants by default." Commented Nov 7, 2017 at 19:08

2 Answers 2

3

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 
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.