天坑啊!Swift的is使用时出现 warning: 'is' test is always true
2016-09-22 21:25
489 查看
今天在写Swift代码的时候,写到把对象存进数组并计算数组里每个类型对象的个数时:(以下为)
使用了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;">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>
相关文章推荐
- iOS获取手机型号,Swift获取手机型号(类似iphone 7这种,能取到具体型号)
- swift 3.0 - 字符串
- swift中跳转WKWebView 链接不含汉字的写法
- swift 中跳转WKWebView,链接含有汉字的写法
- Swift 字符串
- Swift:一个简单的货币转换器App在iOS10中的分析和完善
- Swift:一个简单的货币转换器App在iOS10中的分析和完善
- Swift:一个简单的货币转换器App在iOS10中的分析和完善
- Xcode 8 升级 Swift 3.0 问题。
- 桶排序-Swift
- Swift - 文本框textView图文混排的实现(附样例)
- Swift - Dictionary 基本使用
- swift项目第三天:手写代码搭建主框架
- Swift 3必看:foundation中数据引用类型改为值类型
- Swift 与 JavaScript 的交互
- swift UIImageView
- Swift-iOS常用控件(UIActionSheet 动作列表)
- Swift-iOS常用控件(UIAlertView警告视图)
- SWift-iOS常用控件(UIProcessView进度条)
- Swift-iOS常用控件(UIStepper计数器/步进器)