How to use `some View` as Dictionary member value?

I have a Dictionary with a key who's values need to return a SwiftUI view. I thought at first of doing:

[String:some View] but the compiler complains that `'some' types' can't be used in this way. Ok, then maybe I can use a closure as the value:

[String:() -> some View] but the compiler has issues with this as well: 'some' types are only implemented for the declared type of properties and subscripts and the return type of functions

Any suggestions on how I can look up based upon a key a given View?

some View is opaque and can be any different View types, that's most likely why. Maybe you can use AnyView.

I guess I'm just confused why the error indicates that it is limited as a return type for a function but the closure return type doesn't qualify?

The error indicates that "compound" opaque types are not yet supported. So this means that the following, although reasonable, doesn't work:

var x: Optional<some Collection> { [1, 2, 3] }

Currently, you can only use opaque type as return types (that's why the Swift Evolution proposal is called [SE-0244] Opaque Result Types instead of just Opaque Types). What you're looking for is expressed in the Future Directions section:

I would also add that even with that future direction in place, you wouldn't still be able to use [String: some View], unless the values are all of the same concrete type (e.g. all your views are TupleView<(EmptyView, Text)>), which I doubt is your goal. If you need different types for each key, you then need to use a protocol type or an existential wrapper (AnyView in this case).

1 Like

Thanks, that's very insightful. Considering the perf hit with AnyView I'll have to re-think what I'm architecting.

Terms of Service

Privacy Policy

Cookie Policy