我在 swift中有这个代码:解释多态的想法! //Polymorphismclass Person {var name:String="Guest"var age:Int=0init(name:String) { self.name=name self.age=0}init(name:String, age:Int) { self.name=name self.age=age}func Update(nam
//Polymorphism class Person { var name:String="Guest" var age:Int=0 init(name:String) { self.name=name self.age=0 } init(name:String, age:Int) { self.name=name self.age=age } func Update(name:String) { self.name=name } func Upgrade() { self.age++ } } class Student:Person { var average:Float=100 func IsOk()->Bool { return average > 80 } init(name:String, average:Float) { super.init(name: name) self.average=average } } class Teacher:Person { var Salary:Float=2000 init(name:String, age:Int, Salary:Float){ super.init(name: name, age: age) self.Salary=Salary } func GetNetSalary()->Float { return 0.8*self.Salary } override func Upgrade() { super.Upgrade() Salary*=1.1 // add 10% to salary } } var t1:Teacher=Teacher(name: "Ahmed", age: 28, Salary: 3000) var st1=Student(name:"Test", average: 70) var p1:Person=Person(name: "abc") var p2:Person=Student(name: "Student1", average: 100) //up casting var p3:Person=Teacher(name: "Teacher", age: 40, Salary: 3008) var arr=[t1, st1, p1, p2, p3] //array of persons and teachers and students for instance in arr { if instance is Student {println("This is student")} if instance is Teacher {println("This is teacehr")} }
在for循环的最后我怎么能把这样的条件看看数组中的元素是否只是一个Person?
因为当我输入:
if instance is Person {println("This is a Person")}
这给了我一个错误,因为这个条件总是正确的!
EDITED你在问:
How could I put such a condition to see if an element in the array is only a Person?
在强大的静态类型语言中,您无法访问对象的运行时类型,您无法执行此操作.但是,在Swift中,您可以通过dynamicType方法使用该语言的自反属性来获取此类型.