Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a class with a nested class. I'm trying to access variables of the outer class from within the nested 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'
        }
    }

}

This however, gives me the following error:

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

Is there an elegant way to circumvent this? I was hoping for nested classes to capture the lexical scope, as closures do.

Thanks

like image 278
Charles Fisher Avatar asked Jul 25 '17 16:07

Charles Fisher


2 Answers

you could do something like this

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

}
like image 178
Steve Avatar answered Nov 12 '22 17:11

Steve


Try passing in the variable instead of trying to use it directly.

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

    class Thong{
        func printMe(name: String){
            print(name) 
        }
    }
}
like image 26
trishcode Avatar answered Nov 12 '22 17:11

trishcode