Moritz Moritz - 1 year ago 85
Swift Question

Access self inside individual class

I would like to be able to access

self
in the following closure and always get the following error:
Value of type '(NSObject) -> () -> MyViewController' has no member 'pushViewController'
. I didn't manage to find a solution yet. Could you please help me and explain why I cannot access my current class or rather self?

//description view (try to use all the space... get length of text and adjust size accordingly)
let postDescription: PaddingLabel = {

let entireDescView = PaddingLabel()

//set properties of label

//using library "ActiveLabel"
entireDescView.enabledTypes = [.mention]
entireDescView.mentionColor = UIColor(red: 25/255, green: 153/255, blue: 1, alpha: 1)
entireDescView.handleMentionTap { hotel in
self.pushViewController(of: hotel) //cannot access self here
}

return entireDescView
}()

Answer Source

I think the problem is that closure is inside a computed property definition.

That definition exists before class or struct will be initiated.

You could fix it declaring postDescription as lazy var

public class User
{
    let postDescription: String = {

        return self.saludar() // Error. use of unresolved identifier 'self'
    }()

    internal func saludar() -> String
    {
        return "testing greeeting..."
    }
}

With lazy var...

public class User
{
    lazy var postDescription: String = {

        return self.saludar() // It's OK
    }()

    internal func saludar() -> String
    {
        return "testing greeeting..."
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download