Sitemap

Understanding some in Swift

--

Press enter or click to view image in full size

Imagine you’re at a fruit market. You tell the vendor, “I want some fruit.” The vendor gives you an apple. The key thing here is that you didn’t specify which type of fruit you wanted, but the vendor made the choice and gave you an apple. Next time, the vendor might give you an orange or a banana, but you always know you’ll get a fruit.

In Swift, the keyword some works in a similar way. It tells the compiler, "I want a type that conforms to a specific protocol, but I don't need to know the exact type right now."

The Power of some: Making Your Code Flexible

Let’s say you’re building an app where you have different shapes — circles, squares, triangles — that all conform to a protocol called Shape. You want to create a function that returns any shape, but you're not bothered about the specific type of shape. Here's how some can help:

protocol Shape {
func area() -> Double
}

struct Circle: Shape {
var radius: Double
func area() -> Double {
return .pi * radius * radius
}
}

struct Square: Shape {
var side: Double
func area() -> Double {
return side * side
}
}

func createShape() -> some Shape {
return Circle(radius: 5)
}

In this example, the createShape() function returns some Shape. It doesn't specify what kind of shape, just that it will be a shape that conforms to the Shape protocol. This makes your code more flexible because you can change what specific type is returned without altering the function signature.

Special Cases and Edge Cases

1. Single Type Enforcement:

The some keyword enforces that the type returned by the function is consistent. If you try to return different types (e.g., a Circle sometimes and a Square other times), you'll get a compiler error.

func createAnotherShape(flag: Bool) -> some Shape {
if flag {
return Circle(radius: 5)
} else {
return Square(side: 5) // Error: `some` must always return the same type
}
}

Why? The type must be consistent for Swift to ensure type safety. The compiler needs to know the exact type to manage memory and other resources efficiently.

2. Opaque Return Type:

The some keyword is also known as an "opaque return type." It's called "opaque" because it hides the specific type, but ensures that the returned value conforms to the expected protocol.

Get Harsha Agarwal’s stories in your inbox

Join Medium for free to get updates from this writer.

Edge Case: If your function returns an opaque type (some Shape), you can't do things that rely on knowing the exact type, like using type-specific methods or properties that aren't part of the protocol.

let shape = createShape()
print(shape.radius) // Error: `radius` is not part of the `Shape` protocol

Real-World Use Case: Handling Payments

Consider a payment system where you have different payment methods — credit cards, PayPal, bank transfers — that all conform to a PaymentMethod protocol. You might want a function that returns a payment method based on user preferences:

protocol PaymentMethod {
func pay(amount: Double)
}

struct CreditCard: PaymentMethod {
func pay(amount: Double) {
print("Paid \(amount) using Credit Card")
}
}

struct PayPal: PaymentMethod {
func pay(amount: Double) {
print("Paid \(amount) using PayPal")
}
}

func selectPaymentMethod() -> some PaymentMethod {
return CreditCard() // Could be PayPal, but it's still a `PaymentMethod`
}

In this scenario, the user doesn’t need to know the specific payment method being used. They just care that a payment will be processed, and some allows you to easily swap out the payment method behind the scenes.

Documentation and Further Reading

If you want to dive deeper into the technical aspects of some and its uses, you can check out the official Apple WWDC video.

Conclusion

The some keyword in Swift is a powerful tool that allows you to create more flexible and maintainable code. By using some, you can hide the exact type while still ensuring that the returned value conforms to a protocol. This can be incredibly useful in many real-world scenarios where you want to abstract away the specifics of what’s being returned.

Remember, while some can make your code more adaptable, it does come with the requirement that the type returned is consistent. Understanding this balance will help you make the most out of this feature in Swift. I will be sharing more insights on this topic in future articles, where we’ll dive deeper into how to effectively use these features to enhance your Swift code.

Happy Coding!

--

--

Harsha Agarwal
Harsha Agarwal

Written by Harsha Agarwal

iOS dev sharing my learning journey. I use Medium to stay accountable as I explore Apple's ecosystem. Expect real-world analogies and celebrity website mockups.