如果我有两个具有相同属性名称的显式类,有没有一种方法可以调用该属性而不必定义我正在使用的类?
class firstClass {
var name = “Name”
init…..
}
class secondClass {
var name = “Another name”
init….
}
now another function can call
//does not work... I get an error saying AnyObject doesn't have property
func printNameOf(object: AnyObject) {
println(object.name)
}
//works but my software has a lot of classes, which means a ton of code
func printNameOf(object: AnyObject) {
if object is firstClass {
println((object as firstClass).name)
}
if object is secondClass {
println((object as secondClass).name)
}
}
您可以通过创建两个类都符合的协议来做到这一点:
protocol NameProtocol {
var name: String {get set}
}
class firstClass: NameProtocol {
var name = "Name 1"
}
class secondCLass: NameProtocol {
var name = "Name 2"
}
func printNameOf(obj: NameProtocol) {
// You know obj has property name
println(a.name)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句