我想在类中自己访问类方法。我知道您可以在类实例中使用 self 关键字,如下所示:
class InstanceClass {
var testProperty = "testing"
func testMathod() {
print(self.testProperty)
}
}
// initiate like so
let newInstance = InstanceClass()
newInstance.testMathod() // result testing
在下面的示例中,访问静态属性中的类的关键字是什么:
class BaseClass {
static let testProperty = "test"
class func printProperty () {
// here I want to access testProperty
}
}
我知道我可以在上面的例子中做BaseClass.testProperty,但我想保持抽象。
我正在运行Swift 2.11。
答案 0 :(得分:0)
我的不好.. 自我关键字也适用于类方法。
示例:
class BaseClass {
class var testProperty: String {
return "Original Word"
}
static func printTestPropery() {
print(self.testProperty)
}
}
class ChildClass: BaseClass {
override class var testProperty: String {
return "Modified Word"
}
}
ChildClass.printTestPropery() // prints "Modified Word"
答案 1 :(得分:0)
我发现Swift与此有点不一致,但以下是从各种范围访问静态类属性的方法:
class BaseClass
{
static let testProperty = "test2"
// access class property from class function
class func printProperty()
{
print( testProperty )
}
// access class property from instance function
func printClassProperty()
{
print(BaseClass.testProperty)
print(self.dynamicType.testProperty)
}
}
protocol PrintMe:class
{
static var testProperty:String { get }
}
extension BaseClass:PrintMe {}
extension PrintMe
{
// access from a class protocol can use Self for the class
func printFromProtocol()
{
print(Self.testProperty)
}
}