Greetings, traveler!
There is a type in Swift called CollectionOfOne
, which is a collection of one element. Does it sound weird? Don’t rush to judge.
Check out this example. We can measure the execution time using a benchmark we created in one of the articles.
Note
By the way, if you’d like to learn more about this benchmark, you can do so here.
This function helps us print out the operation’s result value in the console and measure its execution time.
func printCount(of collection: any Collection) {
let benchmark = Benchmark()
print(collection.count)
benchmark.stop()
}
Now, let’s create two collections.
let array = [1]
let collectionOfOne = CollectionOfOne(1)
Now, let’s use our function to print out the count of both collections and check out the measurement result.
printCount(of: array) // 0.02817 sec.
printCount(of: collectionOfOne) // 0.00016 sec.
It looks significant.
We will gain the same result using all methods and variables from the Collection
protocol interface. The reason is that CollectionOfOne’s implementation of these methods and variables contains hardcoded values. Like this:
public var count: Int {
return 1
}
Conclusion
If you want to make your code faster, you can use this type.
If you enjoyed this article, please feel free to follow me on my social media:
It might be interesting:
- Leveraging Enums for Flexible Button Styling in SwiftUI
- How to access UIHostingController from a SwiftUI View
- Simplifying Data Access in SwiftUI with @dynamicMemberLookup
- Three Practical Tools for Managing References and Detecting Memory Leaks in Swift
- Paging with Peek: Three Ways to Implement Paginated Scroll in SwiftUI