您的位置:首页 > 移动开发 > Swift

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

2016-09-22 21:25 489 查看
今天在写Swift代码的时候,写到把对象存进数组并计算数组里每个类型对象的个数时:(以下为)

<span style="font-size:18px;">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 style="font-size:18px;">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 style="font-size:18px;">if st is Person这里恒为真,于是就不能正常进行类型判断。这应该算是一个Swift的漏洞吧,is做得还不够完善。</span>
<span style="font-size:18px;">解决方法是吧父类的Person的比较写在最后:</span>
<span style="font-size:18px;"><pre name="code" class="objc">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 style="font-size:18px;">这样就可以正常进行分类了。。。。。。。</span>


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: