Skip to content

Understanding the 'some' Keyword in Swift

Swift, SwiftUI, Programming1 min read

Swift's introduction of the some keyword brought a significant improvement in the way developers can handle type abstraction and polymorphism. This guide aims to explain the concept of some in Swift and how it can be effectively used in your Swift applications.

What is the some Keyword?

The some keyword in Swift is used to denote an opaque type. Opaque types are particularly useful when you want to hide the concrete type of a returned value but still provide type information.

Advantages of Opaque Types

  • Type Privacy: The concrete type is hidden from the function’s caller, providing an abstraction layer.
  • Consistency: It ensures that the same type is used across multiple calls.
  • Compatibility with Protocols: It works seamlessly with protocols, especially those with associated types.

Using some with Protocols

Let's explore how some can be used with protocols to return a specific implementation.

Protocol Definition

1protocol Drawable {
2 func draw() -> String

Implementations of the Protocol

1struct Circle: Drawable {
2 func draw() -> String {
3 return "Drawing a Circle"
4 }
7struct Square: Drawable {
8 func draw() -> String {
9 return "Drawing a Square"
10 }

Returning an Opaque Type

1func createShape() -> some Drawable {
2 return Circle()

In this example, createShape returns a type that conforms to Drawable, but the actual type (Circle) is hidden from the caller.

Benefits in SwiftUI

In SwiftUI, the some keyword is widely used in view declarations. Here’s an example:

1struct ContentView: View {
2 var body: some View {
3 Text("Hello, SwiftUI!")
4 }

This usage provides flexibility in the UI design, allowing the body property to return different types of views without exposing the exact view type.

Comparing some with Generics

While some provides type abstraction like generics, they serve different purposes:

  • Generics: Allow a function to remain type agnostic.
  • some: Guarantees a specific, but undisclosed, type is returned.

In Closing

The some keyword in Swift offers a powerful way to work with abstract types while ensuring type safety and consistency. It’s particularly useful in protocol-oriented programming and SwiftUI development, allowing for more flexible and maintainable code. Remember, the power of some lies in its ability to combine the benefits of type safety, abstraction, and consistency in your Swift applications.