Reputation: 63
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
Upvotes: 6
Views: 8170
Reputation: 3549
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)
}
}
}
Upvotes: 2
Reputation: 1431
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)
}
}
}
Upvotes: 3