Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI : binding value from function

Tags:

swiftui

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.

like image 907
Chéramy Alexandre Avatar asked Oct 22 '25 11:10

Chéramy Alexandre


1 Answers

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 
  }
like image 51
Asperi Avatar answered Oct 26 '25 02:10

Asperi