4

I would like to binding value from a function. But I have the following error :

Cannot convert value of type 'Int' to expected argument type 'Binding<Int>'

Example code :

struct MyFirstView: View {

  var body: some View {
    MySecondView(index: getIndex())
  }
  
  func getIndex() -> Int {
    /* Code to get the index.... */
        
    return index
  }
}

struct MySecondView: View {
  
  @Binding var index: Int

  var body: some View {
    Text("Current index : ", index)
  }
}

Thanks.

1
  • 1
    Why a Binding? If the value is not being modified in MySecondView just use a standard property let index: Int Commented Mar 18, 2022 at 16:32

1 Answer 1

14

You just need to generate binding on-the-fly in function (if you really need binding there), like

  func getIndex() -> Binding<Int> {
    /* Code to get the index.... */

    return Binding(get: {index}, set: {index = $0})
//    return Binding(get: {index}, set: {_ in }) // alternate 
  }
Sign up to request clarification or add additional context in comments.

Comments

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.