0

I have the following struct:

struct MyStruct {
    var myInt: Int
    var myString: String
}

This struct should be edited in a function like this:

func editMyStruct(action: (inout MyStruct) -> ()) {
    var mutableMyStruct = MyStruct(myInt: 10, myString: "Foo")
    action(&mutableMyStruct)
    //do something with the modified 'mutableMyStruct' ...
}

However, I do have difficulties to call editMyStruct(action: (inout MyStruct) -> ()).

editMyStruct(action: { myStruct in
    myStruct.myInt = 20
    myStruct.myString = "Bar"
})

XCode throws the error:

Type of expression is ambiguous without more context

Does anyone of you know, how to fix this issue?

Looking forward to your response!

Poweranimal
  • 1,622
  • 3
  • 12
  • 16
  • 1
    The behavior of inout closure arguments was changed in I believe Swift 4.0.3. Which version of Swift are you using? Also, are there other overloads of `editMyStruct`? It works fine for me (Swift version 4.0.3, tested in REPL). – Palle Feb 17 '18 at 16:32
  • @Palle Argh! Shame on me. I noticed that the mentioned error was thrown due to having another function with the same signature ... Yeah you're right, the above code is working properly ;) – Poweranimal Feb 17 '18 at 16:40

1 Answers1

0

Found the answer!

The syntax for the editMyStruct(action: (inout MyStruct) -> ()) must be:

editMyStruct(action: { (myStruct: inout MyStruct) in
    myStruct.myInt = 20
    myStruct.myString = "Bar"
})

EDIT

Argh! Shame on me. I noticed that the mentioned error was thrown due to having another function with the same signature ... The code from above is fine ;)

Poweranimal
  • 1,622
  • 3
  • 12
  • 16