2016-01-16 24 views
-1

我想訪問它自己的類中的類方法。我知道你可以使用關鍵字在一個類的實例,像這樣:在類中引用類自己的方法

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運行。

+2

「我想保持它抽象」你能解釋一下嗎? – anhtu

+0

請考慮以下示例:https://gist.github.com/anonymous/46ff24e7adbf95d151fe –

回答

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" 
0

我覺得斯威夫特成爲這個有點抵觸,但這裏是你如何從不同範圍訪問靜態類屬性:

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) 
    } 
} 
相關問題