美文网首页
swift5基本语法-关键字is、as?、as!、as

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

作者: 翀鹰精灵 | 来源:发表于2021-09-25 16:16 被阅读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!

相关文章

网友评论

      本文标题:swift5基本语法-关键字is、as?、as!、as

      本文链接:https://www.haomeiwen.com/subject/xluxnltx.html