I want to display a random view, whether it's the firstScreen, secondSscreen or thirdScreen as seen in the pictures. I tried selecting a random element from my array but that does not seem to work. I hope you can help me! Thank you!
It's because Swift doesn't know what type the value in screens
is.
If you used this:
@State var screens: Array<FirstScreen> = [FirstScreen(), FirstScreen(), FirstScreen()]
Swift would know that screens is an array of FirstScreen
, and so it can supply that view to ContentView
. However, that's clearly not very useful, so you need to wrap it in AnyView
.
Here you go:
struct ContentView : View {
@State var screens: [Any] = [FirstScreen.self, SecondScreen.self, ThirdScreen.self]
var body: some View {
self.buildView(types: self.screens, index: Int.random(in: 0..<screens.count))
}
func buildView(types: [Any], index: Int) -> AnyView {
switch types[index].self {
case is FirstScreen.Type: return AnyView(FirstScreen())
case is SecondScreen.Type: return AnyView(SecondScreen())
case is ThirdScreen.Type: return AnyView(ThirdScreen())
default: return AnyView(FirstScreen())
}
}
}