ios - 在 didSet 中调用函数在类中不起作用

标签 ios swift

我有以下代码在 Playground 上工作。 didSet 观察器按预期工作。

struct itemStruct {
  var name : String = "" {
    didSet (newName) {
      didSetNameTest(name)
    }
  }
}

func didSetNameTest (name : String) {
  println("didSet itemStruct: \(name)")
}
var item = itemStruct()
item.name = "test"

如果我在一个类中移动代码,我会得到一个编译器错误:

class itemClass {
  struct classItemStruct{
    var name : String = "" {
      didSet(newName) {
        didSetClassNameTest(name)
      }
    }
  }

  func didSetClassNameTest(name:String) {
    println("didSet itemClass: \(name)")
  }

  var structItem = classItemStruct()
}

var cItem = itemClass()
cItem.structItem.name = "Test"

错误:无法使用“(String)”类型的参数列表调用“didSelectClassNameTest”

所有代码都可以在 playground 中复制。

最佳答案

由于内部类的实例独立于外部类的任何实例,如@ABakerSmith 评论的链接中所述,对此可能的解决方法是将 didSetClassNameTest 函数设为私有(private)和静态,然后静态调用它 itemClass .didSetClassNameTest(name) 在 didSet 方法上

关于ios - 在 didSet 中调用函数在类中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30601190/

相关文章:

swift - 如何在 RealityKit 中使用 Raycast 方法?

ios - 此类对于键 tradeTextField 不符合键值编码

ios - 在实际旋转之前确定导航栏的新框架 - iOS

ios - UINavigationBar BarTintColor 不适用于 RGB 值

ios - 从 SQLite 检索列到 TableView Swift iOS 单元格中的标签

ios - 从明天开始在 Swift 中安排本地通知每天重复

ios - Eureka 中的动态 TextRow

iOS/swift : Record audio with 16khz on every hardware using AVAudioEngine

iOS Core Data - 当许多上下文同时保存时如何避免崩溃?

ios - 快速使用 map()