Why: Function declares an opaque return type, but the return statements in its body do not have matching underlying types

Viewed 28

Following method raise this error:

Function declares an opaque return type, but the return statements in its body do not have matching underlying types

func showNode(json: JSON) -> some View {
    if let v = json.get() as? String {
        return Text("\(v)").padding()
    } else if let d = json.get() as? [String: JSON] {
        
        return VStack {
            //for kv in d {
            ForEach(d.keys.sorted(), id: \.self) { k in
                if let v = d[k] {
                    Text("\(k)").padding()
                    showNode(json: v)
                }
            }
        }
    } else {
        return Text("").padding()
    }

it uses this type:

public enum JSON {
    case string(String)
    case number(Float)
    case object([String:JSON])
    case array([JSON])
    case bool(Bool)
    
    func get() -> Any {
        switch self {
        case .string(let v):
            return v
        case .number(let v):
            return v
        case .object(let v):
            return v
        case .array(let v):
            return v
        case .bool(let v):
            return v
        }
    }
}

I tried use some AnyView instead of some View.

Strange, method returns either a VStack or Text.


I did changes as proposed post advise: SwiftUI: Function declares an opaque return type, but the return statements in its body do not have matching underlying types

but it raise an other error:

Function opaque return type was inferred as '_ConditionalContent<_ConditionalContent<some View, VStack<ForEach<[Dictionary<String, JSON>.Keys.Element], Dictionary<String, JSON>.Keys.Element, TupleView<(some View, some View)>?>>>, some View>' (aka '_ConditionalContent<_ConditionalContent<some View, VStack<ForEach<Array<String>, String, Optional<TupleView<(some View, some View)>>>>>, some View>'), which defines the opaque type in terms of itself
@ViewBuilder
func showNode(json: JSON) -> some View {
    if let v = json.get() as? String {
        Text("\(v)").padding()
    } else if let d = json.get() as? [String: JSON] {
        VStack {
            ForEach(d.keys.sorted(), id: \.self) { k in
                if let v = d[k] {
                    Text("\(k)").padding()
                    showNode(json: v)
                }
            }
        }
    } else {
        Text("").padding()
    }
}

Do you know maybe what I did wrong?

0 Answers
Related