API Design Question: Auxiliary Function or Extension Function

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() {

// Auxiliary method
func printScores<T: Sequence>(scores: T) where T.Element == Score {

// Call via extension function

// 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!

Since the method only applies to Sequences of Score, it's sensible to make it an extension method.

One benefit of using an extension method is that code completion will only offer it on the appropriate values. If you type "foo".pr, "foo" is a Sequence, but you won't be offered printScores as a completion, because it's not a Sequence of Score. In fact it would be reasonable to just name it print as an extension method.

Terms of Service

Privacy Policy

Cookie Policy