Last active
August 29, 2015 14:05
-
-
Save joshdholtz/c31d7140d9b15fdc87ab to your computer and use it in GitHub Desktop.
Can i pass in a class (not instance of a class), and sure it conforms to a protocol?
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
| // Playground - noun: a place where people can play | |
| import UIKit | |
| var str = "Hello, playground" | |
| protocol Cool { | |
| init(name: String) | |
| func talk() -> String | |
| } | |
| class SoCool: Cool { | |
| var name: String | |
| required init(name: String) { | |
| self.name = name | |
| } | |
| func talk() -> String { | |
| return "I'm \(name) and I'm so cool" | |
| } | |
| } | |
| class JoeCool: Cool { | |
| var name: String | |
| required init(name: String) { | |
| self.name = name | |
| } | |
| func talk() -> String { | |
| return "I'm \(name) and not Joe Cool" | |
| } | |
| } | |
| class NotCool { } | |
| func createCool<T: Cool>(a: T.Type, name: String) -> String { | |
| return T(name: name).talk() | |
| } | |
| createCool(SoCool.self, "Josh") // Returns "I'm Josh and I'm so cool" | |
| createCool(JoeCool.self, "Josh") // "I'm Josh and not Joe Cool" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment