加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 06:43:49 所属栏目:百科 来源:网络整理
导读:今天在写Swift代码的时候,写到把对象存进数组并计算数组里每个类型对象的个数时:(以下为) span style="font-size:18px;"class Person:{}class Teacher:Person{ }class Student:Person{ }var person = Person()var teacher = Teacher()var student1 = Stu

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读