Doing basic reflection in Swift, I encountered a couple of road blocks. The first has to do with static var in a protocol. Isn't it the same as requesting the implementation to define a class var? The second has to do with returning the name of the class when it's passed as type AnyClass? Is this the right thing to do?
protocol Nameable {
static var name: String { get }
}
func nameForClass(cls: AnyClass) -> String {
var name = ""
if (cls as? Nameable != nil) {
name = (cls.self as! Nameable).name
}
if (name.isEmpty) {
name = NSStringFromClass(cls.self)
}
return name
}
class A : Nameable {
static var name: String {
return "ClassA"
}
}
class B : Nameable {
static var name: String {
return ""
}
}
println(nameForClass(A.self) // Should print "ClassA"
println(nameForClass(B.self) // Should print "B"
Aucun commentaire:
Enregistrer un commentaire