Crafting Elegant Swift Code: Beyond the Basics
How to create Swift code that is aesthetically pleasing and, more importantly, self-documenting.
Swift, renowned for its clarity and expressiveness, offers a plethora of features to write code that’s not only functional but also aesthetically pleasing. In this article, we delve into the art of crafting elegant Swift code, exploring techniques that elevate your code from good to great.
Beginner Level
Argument Labels: Enhancing Clarity
Swift’s argument labels are more than mere gimmicks. They serve a crucial role in making your function calls self-documenting. Consider this example:
func count(fruitName: String) {
print(3)
}
// Get the count
count(fruitName: "Apple")
While the function name clearly states that we get the count for a certain fruit, we can make it even more expressive:
func count(of fruitName: String) {
print(3)
}
count(of "Apple")
This looks way better on the calling side and makes the code more readable. Additionally, the of
makes it very clear we need the count of a fruit.