Search code examples
swiftswift2protocolsswift-extensionsswift-protocols

Accessing swift class extension methods from within original class


The below code does not compile for me:

import Foundation  
@objc public protocol MyProtocol {  
    func protocolMethod(parameter: (String)) -> String  
    func anotherProtocolMethod() -> Int  
}  
class MyClass: NSObject {  
    var myValue = self.anotherProtocolMethod()  
}  
extension MyClass: MyProtocol {  
    func protocolMethod(parameter: (String)) -> String {  
        return ""  
    }  

    func anotherProtocolMethod() -> Int {  
        return 1  
    }  
}  

The error occurs on the line myValue is assigned, it reads: error: value of type 'NSObject -> () ->MyClass has no member anotherProtocolMethod

Is there a way to make this work without moving myValue into the class extension?


Solution

  • This has nothing to do with the extension. This line would be illegal in any case:

    var myValue = self.anotherProtocolMethod() // an instance property
    

    A stored instance property cannot be directly initialized by calling an instance method, because at initialization time the instance is exactly what does not yet exist.