Home > Software engineering >  Satisfying var body: some View in protocol extension
Satisfying var body: some View in protocol extension

Time:07-28

I wish to do the following:

import SwiftUI

protocol CombinedView: View {
    var dataForViewA: String { get }
    var viewA: any View { get }
    var viewB: any View { get }
}

extension CombinedView {
    var viewA: Text {
        Text(dataForViewA)
    }
    
    var body: some View {
        VStack {
            viewA
            viewB
        }
    }
}

viewA works fine because I can specify the concrete type, but var body complains:

Type 'any View' cannot conform to 'View'

I am unsure what I need to implement to solve this. Any ideas?

Thanks in advance for any advice

CodePudding user response:

It does not work that way, instead we need associated types for each generic view and specialisation in extension.

Here is fixed variant. Tested with Xcode 14b3 / iOS 16

protocol CombinedView: View {
    associatedtype AView: View
    associatedtype BView: View

    var dataForViewA: String { get }

    var viewA: Self.AView { get }
    var viewB: Self.BView { get }
}

extension CombinedView {
    var body: some View {
        VStack {
            viewA
            viewB
        }
    }
}

extension CombinedView where AView == Text {
    var viewA: Text {
        Text(dataForViewA)
    }
}
  • Related