UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Is it possible to type cast Binding<Any Object> to Binding<Object>

Forums > SwiftUI

Here is what I am working on:

  1. there are 2 kind of Structs, TypeA and TypeB, both conform to a TestProtocol
  2. there are 2 views, viewA and viewB, each of them has a Binding var of TypeA and TypeB
  3. in the mainView, there is an array of [TestProtocol]
  4. I want to use ForEach to present that array.

here is my code:

protocol TestProtocol {
    var testId: String {get set}
}
struct TypeA: TestProtocol{
    var testId: String
    var testString1: String
}
struct TypeB: TestProtocol{
    var testId: String
    var testString2: String
}
struct viewA: View{
    @Binding var a: TypeA
    var body: some View{
        TextField("test", text: $a.testString1)
    }
}

struct viewB: View{
    @Binding var b: TypeB
    var body: some View{
        TextField("test", text: $b.testString2)
    }
}

struct SwiftUIViewForBindingTest: View {
    @State var testArray = [TestProtocol]()

    var body: some View {
        VStack{
            if !testArray.isEmpty{
                ForEach($testArray, id:\.testId){ $item in
                    if item is TypeA{
                        viewA(a: $item as! Binding<TypeA>)
                    }else if item is TypeB{
                        viewB(b: $item as! Binding<TypeB>)
                    }
                }
            }

            Button("add Data"){
                testArray = [TypeA(testId: "a", testString1: "aaaa"), TypeB(testId: "b", testString2: "bbbb")]
            }
        }
    }
}

Xcode gave me the error Cast from 'Binding<any TestProtocol>' to unrelated type 'Binding<TypeA>' always fails on the line viewA(a: $item as! Binding<TypeA>)

I think I shouldn't Type Cast the Binding in this way. How could I convert Binding <any TestProtocal> to Binding<TypeA>, or it's impossible to do that?

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.