"instance member cannot be used on type" 错误 Swift 4 嵌套 类

"instance member cannot be used on type" error on Swift 4 with nested classes

我有一个带有嵌套 class 的 class。我正在尝试从嵌套 class:

中访问外部 class 的变量
class Thing{
    var name : String?
    var t = Thong()

    class Thong{
        func printMe(){
            print(name) // error: instance member 'name' cannot be used on type 'Thing'
        }
    }

}

然而,这给了我以下错误:

instance member 'name' cannot be used on type 'Thing'

有什么优雅的方法可以规避这个问题吗?我希望嵌套的 classes 能够捕获词法范围,就像闭包一样。

谢谢

你可以这样做

class Thing{
    var name : String = "hello world"
    var t = Thong()

    init() {
        t.thing = self
        t.printMe()
    }


    class Thong{
        weak var thing: Thing!

        func printMe(){
            print(thing.name)
        }
    }

}

尝试传入变量而不是尝试直接使用它。

class Thing{
    var name : String?
    var t = Thong()

    class Thong{
        func printMe(name: String){
            print(name) 
        }
    }
}