天坑啊!Swift的is使用时出现 warning: 'is' test is always true

天坑啊!Swift的is使用时出现 warning: 'is' test is always true,第1张

概述今天在写Swift代码的时候,写到把对象存进数组并计算数组里每个类型对象的个数时:(以下为) <span style="font-size:18px;">class Person:{}class Teacher:Person{ }class Student:Person{ }var person = Person()var teacher = Teacher()v

今天在写Swift代码的时候,写到把对象存进数组并计算数组里每个类型对象的个数时:(以下为)

<span >class Person:{}class Teacher:Person{    }class Student:Person{    }var person = Person()var teacher = Teacher()var student1 = Student()var student2 = Student()var arr = [teacher,student1,student2,person]var statistic:[String: Int]=["person" : 0,"teacher" : 0,"student" : 0]</span>

使用了is比较类型:

<span >for st in arr{    if st is Person{         statistic["person"]! = statistic["person"]!+1    }else if st is Student{        statistic["student"]! = statistic["student"]!+1    }else if st is Teacher{        statistic["teacher"]! = statistic["teacher"]!+1    }}</span>


结果出现了

warning: 'is' test is always true 发现代码没有问题啊,于是就找了半天的BUG,终于,大半个小时候,找到了原因:

因为Student类和Teacher类都继承于Person,所以is就把他俩都认为是Person类,于是就在

<span >if st is Person这里恒为真,于是就不能正常进行类型判断。这应该算是一个Swift的漏洞吧,is做得还不够完善。</span>
<span >解决方法是吧父类的Person的比较写在最后:</span>
<span ><pre name="code" >for st in arr{    if st is Teacher{        statistic["teacher"]! = statistic["teacher"]!+1    }else if st is Student{        statistic["student"]! = statistic["student"]!+1    }else if st is Person{         statistic["person"]! = statistic["person"]!+1    }}</span>
<span >这样就可以正常进行分类了。。。。。。。</span>
总结

以上是内存溢出为你收集整理的天坑啊!Swift的is使用时出现 warning: 'is' test is always true全部内容,希望文章能够帮你解决天坑啊!Swift的is使用时出现 warning: 'is' test is always true所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1072048.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存