1

I just started learning SwiftUI, and tried to call a method which returns a View, to a variable of type View, but get this surprising error:

Cannot assign value of type 'some View' 
(result of 'Self.frame(width:height:alignment:)') 
to type 'some View' 
(result of 'Self.fill(_:style:)')

I wanted to try framing a view, just to see what would happen, to understand how SwiftUI arrives at dimensions for things.

    let p = Path({ (path:inout Path) -> () in
        path.addRect(CGRect(
            x:0,
            y:0,
            width:geometry.size.width,
            height:geometry.size.height
        ))
    })
    var result = p.fill(Color.red)
    result = result.frame(width: 100, height: 100)

What I think is happening here is that first I'm creating a struct Path, and calling its fill method turns it into a View. When I set var result to this return value, it should be inferred to have type View, which XCode says it does.

enter image description here

Since the View protocol has a frame(width:height:alignment:) -> some View method, I call that to get a new View. Now since result is inferred to be a View, and I'm assigning to it the result of frame, also a View, shouldn't that be legal?

(On another StackOverflow question someone commented "some View - means one concrete type that conforms to View co it cannot once be MenuView and other time be CreateChannelView.". Could that be the case here? If so, I'd also like know how to see what concrete type a method returns.)

enter image description here

Bemmu
  • 17,849
  • 16
  • 76
  • 93

1 Answers1

1

Instead of

var result = p.fill(Color.red)
result = result.frame(width: 100, height: 100)

use directly combined view as

return p.fill(Color.red).frame(width: 100, height: 100)

The some View means some opaque concrete view type but to use assignment the type must be the same however modifiers .fill and .frame produce different concrete types, that's why your assignment generated error.

Asperi
  • 228,894
  • 20
  • 464
  • 690
  • 2
    Is there a way to declare a variable that can hold anything that conforms to the View protocol? Looks like there used to be `var result:protocol ` but it no longer works. – Bemmu Apr 21 '20 at 13:20