luk2302
luk2302

Reputation: 57114

Explicitly specify generic type constraint when calling function

I am wondering wether or not is possible in Swift to explicitly specify the generic type of a generic function. Assuming I have the following function definition which basically creates an empty array of a generic type T:

func bar<T>() -> [T] {
    return [T]()
}

How would I be able to call it?

var foo = bar()

results in

generic parameter 'T' could not be inferred

which makes total sense since there really is no information to infer anything here.

But unfortunately my attempt at specifying the type constraint explicitly via the following failed as well:

var foo = bar<Int>()

error: cannot explicitly specialize a generic function

Upvotes: 2

Views: 485

Answers (2)

rob mayoff
rob mayoff

Reputation: 385540

The language doesn't allow you to explicitly specialize the function. I don't know why they implemented it that way. You're more likely to get an answer to that question on the swift-users mailing list.

The typical way to fix this is to make the function take the type as an argument:

func bar<T>(_: T.Type) -> [T] {
    return [T]()
}

bar(Int.self)
// Result: [], with type Array<Int>

Upvotes: 3

Martin R
Martin R

Reputation: 539685

What way is there to specify the generic type of the function?

The generic type can be inferred from the context:

func bar<T>() -> [T] {
    return [T]()
}

let val1 = bar() as [Int] // or:
let val2 : [Int] = bar()

(I cannot answer the other questions.)

Upvotes: 5

Related Questions