DEV Community

Oluwasanmi Aderibigbe
Oluwasanmi Aderibigbe

Posted on

2 1

Day 53 of 100 Days of SwiftUI

I just completed day 53 of 100 days of SwiftUI. Today I learnt about type erasure using the AnyView class and also how to save data using CoreData.

We all know you are only allowed to return one kind of view in your SwiftUI function. Sometimes, you need to return multiple kinds of views. That's where AnyView comes in. It allows you to return multiple kinds of views all you have to do is wrap your view with an AnyView. For example, you can use an AnyView like so.

let switch = 3
var body: some View {
    if switch > 3 {
     return AnyView(TextView("View 1))
    } else {
     return AnyView(TextField("View 2"))
    }
}
Enter fullscreen mode Exit fullscreen mode

The code above returns two different kinds of views depending on the value of the switch. You should use AnyView sparingly because they reduce the performance of your app. Since SwiftUi no longer knows what kind of views your functions are returning. It won't be able to make any optimisations.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)