OrangePot
OrangePot

Reputation: 1082

Swift: cast to type returned from type(of:)

I'm writing a function with this signature:

func updateConfigs(key: String, value: Any)

Currently, value is type Any, how do I cast value to the type returned from type(of: value)?

Upvotes: 0

Views: 95

Answers (1)

Jignesh Patel
Jignesh Patel

Reputation: 146

You can use generics function like this

func updateConfigs<T>(key: String, value: T) -> T {

    return value
}

let result = updateConfigs(key: "test", value: 10.2)
print(type(of: result)) // This will print "Double"

Upvotes: 3

Related Questions