Skip to content

Instantly share code, notes, and snippets.

@rothmichaels
Last active November 12, 2015 14:36
Show Gist options
  • Select an option

  • Save rothmichaels/a831496a4e89f9569285 to your computer and use it in GitHub Desktop.

Select an option

Save rothmichaels/a831496a4e89f9569285 to your computer and use it in GitHub Desktop.
Getting the Type from a generic
func magicValue<T>() -> T? {
let type = T.self
switch type {
case _ where type == String.self:
return "hello, world" as? T
case _ where type == Int.self:
// Ask for a number and get the answer to life, the universe, and everything
return 42 as? T
default:
return nil
}
}
let s: String? = magicValue() // == Optional("hello, world")
let i: Int? = magicValue() // == Optional(42)
let a: [String]? = magicValue() // == nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment