1.Any、AnyObject
Swift提供了2种特殊的类型:Any、AnyObject Any:可以代表任意类型(枚举、结构体、类,也包括函数类型) AnyObject:可以代表任意类类型(在协议后面写上: AnyObject代表只有类才能遵守这个协议) 在协议后面写上: class也代表只有类才能遵守这个协议
2.is、as?、as!、as
is用来判断是否为某种类型 as用来做强制类型转换
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 = "Jack"
print(stu is String) // true
stu = Student()
print(stu is Person) // true
print(stu is Student) // true
print(stu is Runnable) // true
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
var data = [Any]() data.append(Int("123") as Any)
var d = 10 as Double
print(d) // 10.0
3.X.self、X.Type、AnyClass
X是类名
X.self是一个元类型(metadata)的指针(8个字节,本质上是OC的isa指针),metadata存放着类型相关信息 ,相当于OC的X.class X.self属于X.Type类型
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
public typealias AnyClass = AnyObject.Type
var anyType2: AnyClass = Person.self
anyType2 = Student.self
ar per = Person()
var perType = type(of: per) // Person.self
print(Person.self == type(of: per)) // true
4.Self与self
self代表当前实例,Self代表当前类型 Self一般用作返回值类型,限定返回值跟方法调用者必须是同一类型(也可以作为参数类型)
class Person {
var age = 1
static var count = 2
func run() {
print(self.age) // 1
print(Self.count) // 2
}
}
protocol Runnable {
func test() -> Self
}
class Person : Runnable {
required init() {}
func test() -> Self { type(of: self).init() }
}
class Student : Person {}
var p = Person()
// Person
print(p.test())
var stu = Student()
// Student
print(stu.test())
|