从Swift中的不同类调用相同的属性?

时间:2014-12-24 20:41:47

标签: swift

如果我有两个具有相同属性名称的显式类,是否有办法调用属性而无需定义我正在使用的类?

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)
    }
}

1 个答案:

答案 0 :(得分:0)

您可以通过创建两个类符合的协议来执行此操作:

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)
}