vasily
vasily

Reputation: 2920

Swift List of Protocols and Generic Methods

I have a structure describing a list of views

struct A<T: View> {
   let view: T.Type
}

struct B<???> {
    let items: [A<???>]
}

And would like to describe the app the following way

let content = [
    B(items: [
         A(view: View1.self),
         A(view: View2.self)
    ])
]

What's the generic type of B? Can I somehow get it to work? The same was as just declaring view as View in Java.

Upvotes: 0

Views: 52

Answers (2)

user652038
user652038

Reputation:

I bet you're not looking to just use metatypes. If you are, the metatype is built into the type. You don't need to store it:

struct A<View: SwiftUI.View> { }

struct B<View: SwiftUI.View> {
  let items: [A<View>]
}

struct View: SwiftUI.View {
  var body: some SwiftUI.View {
    Text("🐢⚔️")
  }
}

let content = [
  B<View>(items: [A(), A()])
]

Otherwise, use Frankenstein's answer. ⚡️

Upvotes: 1

Frankenstein
Frankenstein

Reputation: 16361

You just need this:

struct A<T: View> {
   let view: T
}

struct B<T: View> {
    let items: [A<T>]
}
let content = [
    B(items: [
         A(view: View1),
         A(view: View2)
    ])
]

Upvotes: 1

Related Questions