swift5基本语法-关键字is、as?、as!、as

2021-09-25  本文已影响0人  翀鹰精灵
is 用来判断是否为某种类型;

as 用来做强制类型转换。

is 示例

class Person {}
class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
      
        var obj : Any = 10
        print(obj is Int) //true
        
        obj = "Allison"
        print(obj is String) //true
        
        obj = Person()
        print(obj is Person) //true
  
    }
  
}

as 示例

class Person {}

class Student: Person {
    func run() {
        print("student run")
    }
    
    func study() {
        print("student study")
    }
}

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // as?用法
        var obj : Any = 10
        var stu = obj as? Student
        stu?.run()
        print(stu?.run())
        
        stu = Student()
        // as?用法
        print((stu as? Student)?.study()) //student study
        // as!用法
        print((stu as! Student).study()) //student study

        // as用法
        var data = [Any]()
        data.append(Int("123") as Any)
        print(data.count) // 1
        var data2 = 10 as Double
        print(data2) //10.0
        
    }
}

END!

上一篇 下一篇

猜你喜欢

热点阅读