一、type
// 例如类A中
class A : NSObject {
class func classMethod() {
let type1 = type(of: self) // 为A.type.type
let type2 = self // 为A.type
let type3 = A.self // 为A.type
}
func instanceMethod() {
let type1 = type(of: self) // 为A.type
let type2 = self // 为A的实例
let type3 = A.self // 为A.type
}
}
type对应OC中的Class,是类类型。
二、Self
'Self' is only available in a protocol or as the result of a method in a class
class A : NSObject {
class func classMethod() -> Self {
let dd = Template(type: self)
return dd
}
class func Template<T>(type: T.Type) -> T {
return A() as! T
}
func instanceMethod() -> Self {
return self
}
}
Self当作为类方法返回值,返回的也必须是实例,不过很少这样做罢了。在Swift中self和Self,可以看到Self作为协议方法返回值,返回的也是实例。
复制结论
综上可看出对于Self来说它只是表示特定类型,并且只能用在协议中或者作为某个类的方法的返回值类型,而self在实例方法中代指当前实例,在类方法中则代指当前类。
网友评论