Consider this example:
struct IdentifiedValue<T> {
typealias ID = UUID
var id: ID
var value: T
}
class ValueStore {
func add<T>(_ value: T) -> IdentifiedValue<T>.ID {
let id = nextID()
let identifiedValue = IdentifiedValue(id: id, value: value)
// Do something with identifiedValue…
return id
}
}
What this add(_:)
method does is that it gets a UUID from somewhere, passes it into the IdentifiedValue
initializer and then return that ID.
What is the best way to turn this add(_:)
into a method that takes multiple parameters? I can’t just add the each
and repeat
keywords because then the return
statement isn’t correct (obviously):
func add<each T>(_ value: repeat each T) -> (repeat IdentifiedValue<each T>.ID) {
let id = nextID()
let identifiedValue = repeat IdentifiedValue(id: id, value: each value)
// Do something with identifiedValue…
return id // error
}
The only way I found was to get everything into a single line so the repeat
and each
keywords act on the whole line. This means adding a separate method that does the thing for a single value and calling that.
At first, I tried adding both of the add(_:)
variants and implementing the one that takes a pack by calling the one that takes a single value, but then the compiler says it doesn’t know which version of add(_:)
to call. I could rename one of the two but I ended up using an inner function (where it isn’t confused, I guess due to shadowing) like this:
func add<each T>(_ value: repeat each T) -> (repeat IdentifiedValue<each T>.ID) {
func add<T>(_ value: T) -> IdentifiedValue<T>.ID {
let id = nextID()
let identifiedValue = IdentifiedValue(id: id, value: value)
// Do something with identifiedValue…
return id
}
return (repeat self.add(each value))
}
So my question is: Is there way to write this without a second function?