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

今天在写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>

                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值