协议中的静态变量

2an*_*3th 5 ios swift

我有一个协议 A,它有一个静态变量 x。B 是 A 的实现。在类 CI 中传递 B 的实例并将其分配给 a。我怎样才能从中访问2(B类中x的值)?

protocol A {
 static var x : Int { get }  
}

class B : A {
 static var x: Int {
  return 2 
}
}


class C {
// instance of B is assigned to a. 
let a: A


print(a.x)
}
Run Code Online (Sandbox Code Playgroud)

Cod*_*ent 4

变量static属于类,而不属于实例。您可以通过以下方式参考该课程dynamicType

print(a.dynamicType.x)
Run Code Online (Sandbox Code Playgroud)