当前位置: 代码迷 >> 综合 >> Swift- is、 as?、 as! 、 as 区别
  详细解决方案

Swift- is、 as?、 as! 、 as 区别

热度:45   发布时间:2024-01-29 12:29:11.0

is用来判断是否为某种类型 ,as用来做强制类型转换

一、 is 判断类型

protocol Runnable {func run() }
class Persion {}
class Student:Persion,Runnable{func run() {print("跑起来")}func study(){print("study")}
}//判断类型
var stu: Any = 10
print(stu is Int)//true
stu = "jack"
print(stu is String)//true
stu = Student()
print(stu is Persion)//true
print(stu is Student)//true
print(stu is Runnable)//true

二、as强制转换

protocol Runnable {func run() }
class Persion {}
class Student:Persion,Runnable{func run() {print("跑起来")}func study(){print("study")}
}var stu:Any = 10
(stu as? Student)?.study() // 没有调用
(stu as! Student).study() // 闪退
stu = Student()
(stu as? Student)?.study() //调用
(stu as! Student).study() //调用
(stu as? Runnable)?.run() //调用