Skip to content

Instantly share code, notes, and snippets.

@perlguy99
Last active December 22, 2020 21:36
Show Gist options
  • Save perlguy99/b6bf73fa366421f0bd8f4e65758bb86d to your computer and use it in GitHub Desktop.
Save perlguy99/b6bf73fa366421f0bd8f4e65758bb86d to your computer and use it in GitHub Desktop.
SwiftUI AnyView vs Group: type erasure in practice

SwiftUI

AnyView vs Group: type erasure in practice

SwiftUI in 100 Days

Key Points

  • Type erasure is the process of hiding the underlying type of some data.

    • This is used often in Swift: we have type erasing wrappers such as AnyHashable and AnySequence, and all they do is act as shells that forward on their operations to whatever they contain, without revealing what the contents are to anything externally.
  • In SwiftUI we have AnyView for this purpose: it can hold any kind of view inside it

    • There is a performance cost to using AnyView: by hiding the way our views are structured, we’re forcing SwiftUI to do a lot more work when our view hierarchy changes
  • Group in an alternative that works in some situations.

  • You CANNOT make an array of Group, but you CAN make an array of AnyView

  • If you intend to use type erasure regularly, it’s worth adding this convenience extension:

extension View {
    func erasedToAnyView() -> AnyView {
        AnyView(self)
    }
}
  • With this approach we can treat erasedToAnyView() like a modifier:
Text("Hello World")
    .font(.title)
    .erasedToAnyView()  

This page also has more information on Codable Keys

Codable

  • Codable has flags for things like .convertFromSnakeCase
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment