Home > Enterprise >  Type casting after initialise a view
Type casting after initialise a view

Time:01-15


struct ViewOne<T>: View{
    let value: T

    var body: some View{
        makeBody()
    }

    @ViewBuilder
    func makeBody(){
        if T is Text{
            T
        }else if T is String{
            Text(T)
        }else if T is Color{
            T.opacity(0.3).ignoreSafeArea()
        }
    }
}

I want to make a View accepts a generic type T, and the view renders depends on what protocol that T conforms to. Type specific functions should be accessible. Thanks :)

CodePudding user response:

Your T is Blah tests aren't sufficient. You don't just need to see if T is a Blah. You need to get value as a Blah if its type is Blah. That requires a value as? Blah cast or a value as Blah pattern.

Using casts:

@ViewBuilder
func makeBody() -> some View {
    if let text = value as? Text {
        text
    } else if let string = value as? String {
        Text(string)
    }else if let color = value as? Color {
        color.opacity(0.3).ignoresSafeArea()
    }
}

Using patterns:

@ViewBuilder
func makeBody() -> some View {
    switch value {
    case let text as Text:
        text
    case let string as String:
        Text(string)
    case let color as Color:
        color.opacity(0.3).ignoresSafeArea()
    default:
        EmptyView()
    }
}
  • Related