swift没有嵌套类吗?
例如,我似乎无法从嵌套类访问主类的属性测试。
class master{
var test = 2;
class nested{
init(){
let example = test; //this doesn't work
}
}
}
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句