swift没有嵌套类吗?
例如,我似乎无法从嵌套类访问主类的属性测试.
class master{
var test = 2;
class nested{
init(){
let example = test; //this doesn't work
}
}
}
Run Code Online (Sandbox Code Playgroud)
rob*_*off 82
Swift的嵌套类与Java的嵌套类不同.好吧,它们就像是一种Java的嵌套类,但不是你想到的那种.
在Java中,内部类的实例自动具有对外部类的实例的引用(除非声明内部类static).如果您有外部类的实例,则只能创建内部类的实例.这就是为什么在Java中你会说出类似的东西this.new nested().
在Swift中,内部类的实例独立于外部类的任何实例.就好像Swift中的所有内部类都是使用Java声明的static.如果希望内部类的实例具有对外部类的实例的引用,则必须将其显式化:
class Master {
var test = 2;
class Nested{
init(master: Master) {
let example = master.test;
}
}
func f() {
// Nested is in scope in the body of Master, so this works:
let n = Nested(master: self)
}
}
var m = Master()
// Outside Master, you must qualify the name of the inner class:
var n = Master.Nested(master:m)
// This doesn't work because Nested isn't an instance property or function:
var n2 = m.Nested()
// This doesn't work because Nested isn't in scope here:
var n3 = Nested(master: m)
Run Code Online (Sandbox Code Playgroud)