【问题标题】:Calling a method from a struct within the same class从同一类中的结构调用方法
【发布时间】:2015-06-15 03:27:48
【问题描述】:

我想对类属性进行逻辑组织,以表明它们是一个逻辑单元,并将它们与其他不太紧密相关的类属性区分开来。

我想在我的班级中使用结构来做到这一点。但是,似乎我无法从 struct 属性设置器调用类方法。我得到了似乎是不适当的编译错误:“在调用中缺少参数 #1 的参数”

这好像和calling method from struct in swift不一样 函数在结构中的位置。就我而言,这些方法是通用的,不仅适用于我的结构,而且适用于所有类属性。因此,我不想在结构中移动它们。

您对如何在类中将属性组织成紧密的逻辑单元有什么想法吗?

class MyClass {
    struct MyStruct {
        static var aVarInMyStruct: String? {
            didSet {
                anotherVarInMyStruct = foo()        // This gives compile error "missing argument for parameter #1 in call"
            }
        }
        static var anotherVarInMyStruct: String?
    }

    func foo() {
        println("I am foo()")
    }
}

【问题讨论】:

    标签: swift class struct


    【解决方案1】:

    内部类型MyStruct对其外部类型MyClass一无所知。所以没有可以从MyStruct 调用的foo 函数。为了更好地组织您的代码,我建议您使用// MARK: - whatever this section is cmets。类型不是用来组织代码的。类型在这里为程序创建正确的抽象。

    【讨论】:

      【解决方案2】:

      我修复了你的错误:

           class MyClass {
          struct MyStruct {
              static var aVarInMyStruct: String? {
                  didSet {
                      anotherVarInMyStruct = MyClass.foo()        // This gives compile error "missing argument for parameter #1 in call"
                  }
              }
              static var anotherVarInMyStruct: String?
          }
      
          static  func foo()->String {
              println("I am foo()")
              return "it is ok"
          }
      }
      

      【讨论】:

      • 这甚至不编译
      • 对不起,我忘记添加返回值了,现在可以使用了
      • 静态关键词也替换为class
      猜你喜欢
      • 1970-01-01
      • 2014-07-22
      • 1970-01-01
      • 2017-10-17
      • 1970-01-01
      • 1970-01-01
      • 2016-10-22
      • 2013-10-08
      相关资源
      最近更新 更多