Swift—— is和 as、 as? 、 as! 区别

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 20:37   2517   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
例2
 let btn = UIButton(type: .custom)
 print((btn is UIButton)) //true
 print((btn is UIControl))//true
 print((btn is UIView))//true
 print((btn is UILabel))//false

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

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP