Caleb Kleveter
Caleb Kleveter

Reputation: 11494

Return any type from a function in Swift

I am attempting to create a function that can return any type. I do not want it to return an object of type Any, but of other types, i.e. String, Bool, Int, etc. You get the idea.

You can easily do this using generics in this fashion:

func example<T>(_ arg: T) -> T {
    // Stuff here
}

But is it possible to do it without passing in any arguments of the same type? Here is what I am thinking of:

func example<T>() -> T {
    // Stuff here
}

When I try to do this, everything works until I call the function, then I get this error:

generic parameter 'T' could not be inferred

Upvotes: 2

Views: 3387

Answers (1)

JeremyP
JeremyP

Reputation: 86691

is it possible to do it without passing in any arguments of the same type?

The answer is yes, but there needs to be a way for the compiler to infer the correct version of the generic function. If it knows what it is assigning the result to, it will work. So for instance, you could explicitly type a let or var declaration. The below works in a playground on Swift 3.

protocol Fooable
{
    init()
}

extension Int: Fooable {}
extension String: Fooable {}

func foo<T: Fooable>() -> T
{
    return T()
}

let x: String = foo() // x is assigned the empty string
let y: Int = foo()    // y is assigned 0

Upvotes: 4

Related Questions