2

View protocol is defined like this:

public protocol View : _View {

    /// The type of view representing the body of this view.
    ///
    /// When you create a custom view, Swift infers this type from your
    /// implementation of the required `body` property.
    associatedtype Body : View

    /// Declares the content and behavior of this view.
    var body: Self.Body { get }
}

so View is now a PATed protocol, which can't be used as a return type directly, though swift 5.1's opaque return type can handle this, but why declare a associatedtype Body : View, not var body: View { get } directly?

limboy
  • 3,879
  • 7
  • 37
  • 53

2 Answers2

1

Because if it is just a var body: Self.Body { get } - your entity, that implements View protocol, will not know the type of the body.

struct MyView: View {
    var body: MyAnotherView {
        //implementation...
    }
}

This code will not compile and you would have to write this:

struct MyView: View {
    var body: View {
        //implementation...
    }
}

And I think behind the scenes SwiftUI has to know the exact type of a View, not just a protocol

Argas
  • 1,427
  • 1
  • 10
  • 12
0

Prior to SwiftUI Swift doesn’t allow us to use protocols with associated types as return types but We can use “regular” protocols. Compiler let you restrict by showing below error:

“Protocol can only be used as a generic constraint because it has Self or associated type requirements.”

What does it mean?

  • Compiler cannot infer the associated type from this definition and the return type would be incomplete.

  • Whenever we call the that function it always return different concrete type instead if same concrete type.

    • Compiler will not let you to perform the swapping, equal, compare operation on this concrete type. Even they adopt the same Protocol ( i.e it's PAT). Because concret type may have different associated type that they fulfilled or use.

    To avoid the different concrete type as return type at each call we use some keyword as opaque return type.

Opaque return type:

  1. It's reverse of generic type.
  2. It always return same concrete type.you and compiler know it.
  3. If we use an opaque result type instead, we enforce that the function will always return the same concrete type.
  4. Inside function while performing the operation we know the generic type.
  • This doesn't answer the question. You are just explaining what the some keyword is, what already is covered exhaustively in https://stackoverflow.com/questions/56433665/what-is-the-some-keyword-in-swiftui. – J. Doe Jun 30 '19 at 15:21