//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(name:String) { self.name=name}func Upgrade() { self.age++}}class Student:Person{var average:float=100func IsOk()->Bool { return average > 80}init(name:String,average:float) { super.init(name: name) self.average=average}}class Teacher:Person {var Salary:float=2000init(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 castingvar p3:Person=Teacher(name: "Teacher",age: 40,Salary: 3008)var arr=[t1,st1,p1,p2,p3] //array of persons and teachers and studentsfor 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方法使用该语言的自反属性来获取此类型.
总结以上是内存溢出为你收集整理的Swift中的多态性(如果没有)全部内容,希望文章能够帮你解决Swift中的多态性(如果没有)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)