It's very possible I'm just doing it wrong. I'm trying to create a coalesce
function in Swift, really just as an exercise in learning the language. I want to make it as generic as possible, so I want to be able to coalesce
any SequenceType
. Here's what I have, with overloads:
func coalesce(S: SequenceType, T: @autoclosure () -> Any? where S.Generator.Element == T>(values: S) -> Any? {
for value: () -> Any? in values {
if let found = value() {
return found
}
}
return nil
}
func coalesce(values: @autoclosure () -> Any?...) -> Any? {
return coalesce(values)
}
The compiler tells me that T
is not convertible to () -> Any?
and further that it "expected a type name or protocol composition restricting T
."
Now, I understand what this means. The compiler is telling me that function types are not eligible to be used as generic type constraints. If true, this is a real shame. One of the things I really love about Swift is that it does not commit the sin of having a bifurcated type system when it comes to nullability. But it looks like it does bifurcate the type system when it comes to function types. They are treated differently. And this means that writing highly general code around function types becomes very difficult if not impossible.
I could of course write this, but this is not general enough for my taste:
func coalesce(values: [@autoclosure () -> Any?]) -> Any?
Anyone know how to achieve something like this using SequenceType
? I am considering filing a bug with Apple about this.
In this case, typealias
do the trick.
typealias AutoclosuredOptionalAny = @autoclosure () -> Any?
func coalesce<S: SequenceType where S.Generator.Element == AutoclosuredOptionalAny>(values: S) -> Any? {
for value: AutoclosuredOptionalAny in values {
if let found = value() {
return found
}
}
return nil
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments