Last active
November 12, 2015 14:36
-
-
Save rothmichaels/a831496a4e89f9569285 to your computer and use it in GitHub Desktop.
Getting the Type from a generic
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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