Passing String array to a function

2k Views Asked by At

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

3

There are 3 best solutions below

0
On BEST ANSWER

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

}
0
On

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.

1
On

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

var array = [String]()