1

So...what I mean is:

class Test {
var a: String?
var b: String?
}

is it possible to have a function that updates either a or b based on an argument?

a bit like

func updateTest(_ attribute: Test.attribute,_ updateTo: String){

attribute = updateTo
}

then call like:

var test = Test()
updateTest(test.b, "foo")
print(test.b) // foo
LateNate
  • 763
  • 9
  • 22

2 Answers2

1

Yes, you can do this with an inout parameter:

func updateTest(_ attribute: inout String?, _ updateTo: String) {
    attribute = updateTo
}

and then:

updateTest(&test.b, "foo")

For the meaning of & here, see What does an ampersand (&) mean in the Swift language?.

Community
  • 1
  • 1
Emil Laine
  • 41,598
  • 9
  • 101
  • 157
0

No, you can't do that. But you could do

func updateTest(_ testClass: Test,_ updateTo: String){
    testClass.b = updateTo
}

So your code would be

var test = Test()
updateTest(test, "foo")
print(test.b) // foo
dst3p
  • 1,008
  • 11
  • 25