The new SwiftUI tutorial has the following code:
struct ContentView: View {
var body: some View {
Text(
Hamish's answer is pretty awesome and answers the question from a technical perspective. I would like to add some thoughts on why the keyword some is used in this particular place in Apple's SwiftUI tutorials and why it's a good practice to follow.
some is Not a Requirement!First of all, you don't need to declare the body's return type as an opaque type. You can always return the concrete type instead of using the some View.
struct ContentView: View {
var body: Text {
Text("Hello World")
}
}
This will compile as well. When you look into the View's interface, you'll see that the return type of body is an associated type:
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 }
}
This means that you specify this type by annotating the body property with a particular type of your choice. The only requirement is that this type needs to implement the View protocol itself.
That can either be a specific type that implements View, for example
TextImageCircleor an opaque type that implements View, i.e.
some ViewThe problem arises when we try to use a stack view as the body's return type, like VStack or HStack:
struct ContentView: View {
var body: VStack {
VStack {
Text("Hello World")
Image(systemName: "video.fill")
}
}
}
This won't compile and you'll get the error:
Reference to generic type 'VStack' requires arguments in <...>
That's because stack views in SwiftUI are generic types!