What is "some" in Swift?

·

3 min read

Every time we create a Swift project using SwiftUI, we can see:

import SwiftUI

@main
struct LandmarksApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Hello, world!")
    }
}

But, what does "some" mean? How does it work?
Today, I will show you what the "some" keyword is in both SwiftUI and Swift.

What the "some" keyword is in Swift

In Swift, the "some" keyword is used in the context of opaque types. Like generics, we can specify a type constraint without using specific concrete type.

Let me explain the details with examples.

func createTriangle() -> Triangle {
    return Triangle()
}

func drawTriangle(triangle: Triangle) -> {
    // some codes to draw triangle
}

func createRectabgle() -> Rectabgle {
    return Rectabgle()
}

func drawTriangle(rectabgle: Rectabgle) -> {
    // some codes to draw rectabgle
}

With code like the above, we have to define functions every time we want to create shapes other than rectangle and triangle. To prevent this, we can utilize the powerful feature of Swift called "protocol".

protocol Shape {
    // some codes to define Shape
}

Wouldn't it be better if we could use the protocol for the return value and the parameter of the function so that the return value and the parameter are conformed to the protocol? This is where the "some" keyword comes in handy.

func createShape -> some Shape {
    // code to create and return a shape
}

func drawShape(shape: some Shape) -> {
    // code to draw the shape
}

By using some Shape as the return value and the parameter, we can indicate that the function returns a value and accept a parameter that conforms to the "Shape" protocol without specifying any concrete type like "Triangle" or "Rectangle". In that sense, the "some" keyword provides an abstraction layer similar to the functionality of generics.

How the "some" keyword works in SwiftUI

Now, let's see how it works in SwiftUI.

Let's look at the default code of SwiftUI again:

import SwiftUI

@main
struct LandmarksApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Hello, world!")
    }
}

When it comes to "some View" in SwiftUI, it can render any components that conforms to the "View" protocol like "Text", "Button", "VStack"/"HStack", "NavigationView" and so on. Therefore, the "some View" is used for the return value of the computed property "body".

Similarly, "some Scene" works in the same way as "some View". The return value can be anything that conforms to the "Scene" protocol (in this case, "WindowGroup" is returned).