Unrestricting explicit declarations of function generics

deleted [quote="fenginsc, post:15, topic:76126, full:true"]

So passing a generic type to a function doesn't break the restriction that the function's generic type must be in the function's signature, it just provides a better and more intuitive syntax to avoid using as.

[/quote]

I think it may break that restriction. For example, how would you implement the following function?


func foo<T>() -> T {
    // how to implement this?
}

let value = foo<Int>()

I think your original example is a special case. The above example is more realistic.

BTW, @mpangburn's example has typo. defaulted's type should be Int.Type, instead of Int. Also, that example doesn't show the advantage of the "passing type parameter explicitly" approach, because @fenginsc's example could do the same.


EDIT: on a second thought, it's possible to implement the above code if T conforms to some protocol. Without constraints, there is no way to implement @scanon's getOne() function too.

Fixed, thanks!

The code in the original post can also have its return type inferred from its caller’s context. My intention was to note a third spelling (alongside as Int.Type or : Int.Type) for type specification; Joe’s note above about the explicit type argument not needing to agree with the actual return type shows it’s not identical, though.

1 Like