Penguinlay
Penguinlay

Reputation: 37

Passing a class's properties to class method selectively in Swift

struct Bar
{
    var one:[Int] = []
    var two:[Int] = []
    var tri:[Int] = []
}

class foo
{
    var bar = Bar()

    func setupBar()
    {
        bar.one = [1]
        bar.two = [2,2]
        bar.tri = [3,3,3]
    }

    //bars are updated here
    func updateBars()
    {
        updateBar(bar.one, bar.two) //...here...
        updateBar(bar.two, bar.tri) //...here...
        //etc...
    }

    //Bar1 should be concatenated with Bar2, and thus Bar1 will be updated.
    func updateBar(_bar1:[Int], _bar2:[Int]) //...here...
    {

    }

In the above example, what is the correct syntax for parameters of updateBar method in both definition and calling?

I tried using inout, but it didn't work either.

Upvotes: 0

Views: 45

Answers (2)

Laura Calinoiu
Laura Calinoiu

Reputation: 714

You are on the right track of using inout, just do not forget to have an &, at calling.

So, declare the function like this:

func updateBar(_ bar1: inout [Int], _ bar2:[Int])

And call like this:

updateBar(&bar.one, bar.two)

I've also put some code:

struct Bar
{
    var one:[Int] = []
    var two:[Int] = []
    var tri:[Int] = []
}

class foo
{
    var bar = Bar()

    func setupBar()
    {
        bar.one = [1]
        bar.two = [2,2]
        bar.tri = [3,3,3]
    }

    //bars are updated here
    func updateBars()
    {
        updateBar(&bar.one, bar.two) //...here...
        updateBar(&bar.two, bar.tri) //...here...
    }

    //Bar1 should be concatenated with Bar2, and thus Bar1 will be updated.
    func updateBar(_ bar1: inout [Int], _ bar2:[Int]) //...here...
    {
        bar1.append(contentsOf: bar2)
    }
}

let f = foo()
f.setupBar()
f.updateBars()

Upvotes: 1

dirkgroten
dirkgroten

Reputation: 20682

Function parameters have an argument label and a parameter name. If you don't specify an argument label the calling function must use the parameter name to specify the parameter. So if you define

func updateBar(bar1:[Int], bar2:[Int]){}

you have to call your function like so:

updateBar(bar1: bar.one, bar2: bar.two)
# in your case you should have called updateBar(_bar1: bar.one, _bar2: bar.two)

If you want to omit the argument label in the calling function, you should explicitly mark it as omitted using _:

func updateBar(_ bar1: [Int], _ bar2: [Int]){}  # note space between _ and bar1

Now you can call your function without argument labels:

updateBar(bar.one, bar.two)

Upvotes: 0

Related Questions