访问self内部闭包返回类型的单个类

时间:2017-07-26 12:02:31

标签: ios swift closures self

我希望能够在以下闭包中访问self并始终收到以下错误:Value of type '(NSObject) -> () -> MyViewController' has no member 'pushViewController'。我还没有找到解决方案。你能帮我解释一下为什么我无法访问我现在的班级或者自己吗?

//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
}()

1 个答案:

答案 0 :(得分:3)

我认为问题在于闭包在计算属性定义中。

该定义在类之前存在或将启动struct。

您可以修改它,将postDescription声明为lazy var

public class User
{
    let postDescription: String = {

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

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

使用lazy var ...

public class User
{
    lazy var postDescription: String = {

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

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