swift类型转化

swift类型转换is和as

旧时模样 提交于 2020-05-02 10:52:09
Swift中类型转换使用 is 和 as 操作符。使用这两个操作符可以检查值的类型或者转换他的类型 一、类型检查 class Animal: NSObject { var name: String! init(name: String) { self.name = name } } class Dog: Animal { var color: UIColor! init(name: String,color: UIColor) { self.color = color super.init(name: name) } } class Cat: Animal { var weight: Float! init(name: String,weight: Float) { self.weight = weight super.init(name: name) } } let animals = [Dog.init(name: "tiger", color: UIColor.yellow), Dog.init(name: "wangcai", color: UIColor.black), Cat.init(name: "hellokitty", weight: 10.0)] 如上创建三个类: Animal,Dog,Cat ,其中Cat和Dog继承与Animal 。创建了一个容器