0

I'm getting Global buffer overflow crashes when I define SwiftUI view's with the some View type. The crashes go away when I use the exact types.

This crashes: let txt: some View = Text("Hi")

This works: let txt: Text = Text("Hi")

Any ideas? Thanks in advance.

WaltersGE1
  • 813
  • 7
  • 26
  • What is the use case of trying to name it with `some View`? ` – jnpdx Feb 11 '21 at 22:36
  • I've have an app that has a few custom buttons, texts, images, etc that are used multiple times. I'm simple defining these elements in a separate file it's in this file where the crashes happen. If I create a file that just have `import SwiftUI` and `let txt: some View = Text("Hi")`, its crashes when I try to use `txt` somewhere else. – WaltersGE1 Feb 12 '21 at 00:09
  • But why define it as `some View` and not just `Text`? – jnpdx Feb 12 '21 at 00:10
  • Because I need to define more complex reusable components where the methods used to customize the component returns `some View` instead of the actual concrete type. For example, `let txt: Text = Text("Hi").frame(width: 20, height: 20, alignment: .center)` doesn't compile because frame has the return type of `some View`. – WaltersGE1 Feb 12 '21 at 00:23
  • Yeah, I figured it might be something like that. It just sounds like fighting the compiler to me. Will post a possible solution – jnpdx Feb 12 '21 at 00:28

1 Answers1

1

Opaque types don't seem to be made for definitions like this. There's a lot of interesting information about this on this SO thread: What is the `some` keyword in Swift(UI)?

You can type the variable as AnyView and use AnyView() to wrap/type erase the content -- then you can use any modifiers you want.

let txt: AnyView = AnyView(Text("Hi").frame(width: 20, height: 20, alignment: .center))

I particularly like this extension to make it look a little cleaner:

extension View {
    func eraseToAnyView() -> AnyView {
        return AnyView(self)
    }
}

let txt: AnyView = Text("Hi").frame(width: 20, height: 20, alignment: .center).eraseToAnyView()
jnpdx
  • 45,847
  • 6
  • 64
  • 94