I'm writing code that consumes a type that conforms to Sequence
and has uses a specific element type.
In this example I'll declare two variables one a Set
of Score
's and another is an Array
of Score
's. I declare two separate functions that process them using two different approaches:
// Declare Sequence Types
var arr = [Score]()
arr.append(contentsOf: [score1, score2])
var aSet: Set = Set(arr)
// Only process if elements are of type Score.
// Extension on base type.
extension Sequence where Element == Score {
func printScores() {
print(self)
}
}
// Auxiliary method
func printScores<T: Sequence>(scores: T) where T.Element == Score {
print(scores)
}
// Call via extension function
arr.printScores()
aSet.printScores()
// Call via auxiliary function
printScores(scores: arr)
printScores(scores: aSet)
Both of these approaches accomplish the same result. This leads me into my main question(s):
In the context of design, are methods via extensions on a specific type more suitable, or are auxiliary functions that operate on a type more suitable?
Which one is more in line with the design of Swift?
When would we prefer to use one approach over another?
Any advice would be greatly appreciated, Thanks!