Skip to content

Instantly share code, notes, and snippets.

@joshdholtz
Last active August 29, 2015 14:05
Show Gist options
  • Select an option

  • Save joshdholtz/c31d7140d9b15fdc87ab to your computer and use it in GitHub Desktop.

Select an option

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?
// 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