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() //调用