Reputation: 1509
I have some code which I'm trying to make generic, and can't quite figure out how.
func randomInt() -> Int { return Int(arc4random_uniform(42)) }
let closures = [randomInt, randomInt, randomInt, randomInt]
let result = closures.map { $0() }
print(result)
In essence, I want to take an array of closures, that return some value of type T
, and return an array of type [T]
with all the results.
This is my attempt:
extension Sequence where Element == () -> T
{
func callAll() -> [T]
{
return self.map { $0() }
}
}
However, this clearly doesn't work, as T
is undefined. How would I go about writing this extension?
Upvotes: 1
Views: 63
Reputation: 54735
You can make the generic callAll
function work only on Sequence
s, where Element
is of type ()->T
, but as far as I know, you cannot declare a generic type in a where clause to an extension.
extension Sequence {
func callAll<T>() -> [T] where Self.Element == ()->T{
return self.map { $0() }
}
}
func randomInt() -> Int { return Int(arc4random_uniform(42)) }
let closures = [randomInt, randomInt, randomInt, randomInt]
let result = closures.callAll()
print(result) //one sample output: [41, 19, 15, 36]
Upvotes: 1