1

I am trying to pass an array to a function:

var array:[String] = []
// fill the array
array.append(uniqueId as String)
// pass the array to a function:
GamePrefrences.setLevelsArray(array)

My function is declares like this:

func setLevelsArray(arr:[String])
{
    GamePrefrences.levels_array = arr

}

But on the line i try to call the function it gives with an error:

cannot invoke ... with argument list of type [(String)]

What is the problem? if its possible to provide brief explanation

1
  • do you know how arrays and dictionary are passed in Swift? Commented Jun 15, 2015 at 7:19

3 Answers 3

3

First of all, your function is not a class level function and you are calling the method directly using class name.

Try like this.

var array:[String] = []
// fill the array
array.append(uniqueId as! String)
// pass the array to a function:
GamePrefrences.setLevelsArray(array)

Function declaration.

  class func setLevelsArray(arr:[String])
    {
        GamePrefrences.levels_array = arr

    }

or,

var array:[String] = []
// fill the array
array.append(uniqueId as String)
// pass the array to a function:
let instance = GamePrefrences()//Depends on you, how you defined the initialiser.
instance.setLevelsArray(array)

Your function body.

func setLevelsArray(arr:[String])
{
    instance.levels_array = arr

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

Comments

0

please try something like this

func setLevelsArray(arr:[String])
{
let tempArr = arr
    GamePrefrences.levels_array = tempArr

}

in Swift Arrays and Dictionary are passed by value not by reference, therefore if you are not changing the values or assigning to any other variable then Swift compiler does not get the copy, instead the variable still lives in the heap. so before assigning i believe it is necessary to copy this into another variable.

Comments

0

You have invalid declaration of an empty array. Here's how to declare empty array:

var array = [String]()

1 Comment

we can also declare the way Michael did. :)

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.