美文网首页
Swift一些关键字

Swift一些关键字

作者: alfei13 | 来源:发表于2021-05-20 16:35 被阅读0次

一、is、as?、as!、as

  • is用来判断是否是某种类型
protocol Runnable {
    func run()
}

class Person {}

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

var stu: Any = 10

print(stu is Int) // true
stu = "Kac"
print(stu is String) // true
stu = Student()
print(stu is Person) // true
print(stu is Student) // true
print(stu is Runnable) // true
  • as用来做强制转换
var stu: Any = 10
(stu as? Student)?.study() // 没有调用study
stu = Student()
(stu as? Student)?.study() // Student study
(stu as! Student).study() // Student study
(stu as? Runnable)?.run() // Student run

二、X.self、X.Type、AnyClass

  • X.self 是一个元类型(metadata)指针,metadata存放着类型相关信息
  • X.self 属于X.Type
  • public typealias AnyClass = AnyObject.Type
  • AnyClass 即任意类类型
class Person {}
class Student : Person {}
var perType: Person.Type = Person.self
var stuType: Student.Type = Student.self
perType = Student.self

var anyType: AnyObject.Type = Person.self
anyType = Student.self

var anyType2: AnyClass = Person.self
anyType2 = Student.self
  • 可以利用type(of: obj) 查一个对象的类型
var per = Person()
var perType = type(of: per)  // Person.self
print(Person.self == type(of: per)) // true

三、元类型的应用

  • 多态
class Animal {
    required init() {}
}
class Cat: Animal {}
class Dog: Animal {}
class Pig: Animal {}

func create(_ clses: [Animal.Type]) -> [Animal] {
    var arr = [Animal]()
    for cls in clses {
        arr.append(cls.init())
    }
    return arr
}
print(create([Cat.self, Dog.self, Pig.self]))
  • 在使用有些系统方法时
print(class_getSuperclass(Animal.self)!) // Swift._SwiftObject

四、Self

  • Self 代表当前类型
  • 可以用来调用类属性、方法
class Animal {
    var age = 1
    static var count = 2
    required init() {}
    func run() {
        print(self.age) // 1
        print(Self.count) // 2
    }
}
  • Self 一般用作返回值类型,限定返回值跟方法调用者必须是同一个类型(也可以作为参数类型)
protocol Runnable {
    func run() -> Self
}

class Animal : Runnable {
    required init() {}
    
    func run() -> Self {
        type(of: self).init()
    }
}

class Cat: Animal {}
class Dog: Animal {}

var a = Animal()
// a type is Animal
print("a type is ", a.run())
var d = Dog()
// d type is Dog
print("d type is ", d.run())

相关文章

网友评论

      本文标题:Swift一些关键字

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