Swift嵌套类属性 [英] Swift nested class properties

查看:128
本文介绍了Swift嵌套类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

swift没有嵌套类吗?

Does swift not have nested classes??

例如,我似乎无法从嵌套类访问主类的属性测试。

For example, I can't seem to access the property test of the master class from the nested class.

class master{
  var test = 2;

  class nested{
     init(){
       let example = test; //this doesn't work
     }
   }
 }


推荐答案

Swift的嵌套类与Java的嵌套类不同。好吧,它们就像是一种Java的嵌套类,但不是你想要的那种。

Swift's nested classes are not like Java's nested classes. Well, they're like one kind of Java's nested classes, but not the kind you're thinking of.

在Java中,内部类的一个实例自动有一个引用外部类的实例(除非内部类声明为 static )。如果您有外部类的实例,则只能创建内部类的实例。这就是为什么在Java中你会说像 this.new nested()

In Java, an instance of an inner class automatically has a reference to an instance of the outer class (unless the inner class is declared static). You can only create an instance of the inner class if you have an instance of the outer class. That's why in Java you say something like this.new nested().

在Swift中,一个实例内部类独立于外部类的任何实例。就像使用Java的 static 声明Swift中的所有内部类一样。如果您希望内部类的实例具有对外部类的实例的引用,则必须使其明确:

In Swift, an instance of an inner class is independent of any instance of the outer class. It is as if all inner classes in Swift are declared using Java's static. If you want the instance of the inner class to have a reference to an instance of the outer class, you must make it explicit:

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)

这篇关于Swift嵌套类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆