简体   繁体   中英

SwiftUI: How to loop through the various structs with various codes, using ForEach?

Supposed, I have three structs named "s001", "s002", "s003". Is it possible to use ForEach loop, which iterate these structs, without appending them into array?

Below the sample code, looping only one struct (s001). Is it possible to use dynamic struct names like "s00+(index)" or something like that?

import SwiftUI

struct ContentView: View {


var body: some View {
    ForEach((1...3), id: \.self) {index in
               AnyView(s001())

    }

  }
}

struct s001: View {var body: some View {Rectangle().foregroundColor(.red)}}
struct s002: View {var body: some View {Circle().foregroundColor(.blue)}}
struct s003: View {var body: some View {Ellipse().foregroundColor(.yellow)}}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
     }
}

Using AnyView is possible but has performance drawback, so for the described scenario, as it should not be too many such structs, the appropriate approach would be to use something like view-factory-builder function, like below

演示

struct S00ContentView: View {

    var body: some View {
        ForEach((1...3), id: \.self) {index in
            self.buildView(for: index)
        }
    }

    func buildView(for id: Int) -> some View {
        Group {
            if id == 1 {
                s001()
            }
            else if id == 2 {
                s002()
            }
            else if id == 3 {
                s003()
            }
        }
    }
}

struct s001: View {var body: some View {Rectangle().foregroundColor(.red)}}
struct s002: View {var body: some View {Circle().foregroundColor(.blue)}}
struct s003: View {var body: some View {Ellipse().foregroundColor(.yellow)}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM