ios - 在 Swift 中定义一个只读属性

标签 ios swift xcode uiview xcode8

如何在 Swift 中定义只读属性?我有一个需要定义公共(public)属性的父类,例如。 项目数。这是我的代码:

Class Parent: UIView {
  private(set) var itemCount: Int = 0
}

class Child {
  private(set) override var itemCount {
    get {
      return items.count
    }
  }
}

我收到错误:无法使用只读属性覆盖可变属性


选项 1 - 协议(protocol):

我不能使用协议(protocol),因为它们不能从类 (UIView) 继承

选项 2 - 组合:

我将 var view = UIView 添加到我的 Child 类,并从我的 Parent 类中删除 UIView 继承。这似乎是唯一可能的方法,但在我的实际项目中,这似乎是错误的做法,例如。 addSubview(myCustomView.view)

选项 3 - Child 类的子类 UIView

我也不能这样做,因为我打算拥有多个具有不同属性和行为的相关 Child 类,并且我需要能够声明我的 Child 的实例> 类作为 Parent 类,以利用 UIView 的属性和 Parent 的公共(public)属性。

最佳答案

您可以使用一个Computed Property,它(就像一个方法)可以被覆盖。

class Parent: UIView {
    var itemCount: Int { return 0 }
}

class Child: Parent {
    override var itemCount: Int { return 1 }
}

更新(作为对下面评论的回复)

这就是你声明和覆盖一个函数的方式

class Parent: UIView {
    func doSomething() { print("Hello") }
}

class Child: Parent {
    override func doSomething() { print("Hello world!") }
}

关于ios - 在 Swift 中定义一个只读属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38318117/

相关文章:

ios - 明确 NSNotification 的 addObserver 函数中 notificationSender 的用途

iphone - 框架改变时得到回调

swift - 通过 transform.scale 属性动画化 CAShapeLayer 的路径

xcode - faSTLane 无法安装在我的 imac 上

ios - 在 <file>.podspec.json 中找不到 ... 的 podspec

ios - Fabric Crashlytics Beta 不断要求分发旧版本

ios - 如何在多个 View 中使用来自单例的一个回调

jquery - Phonegap Jquery Mobile 和 Xcode

ios - Alamofire 发布请求错误调用中的额外参数 'method'

xcode - Swift 2 以 NSException 类型的未捕获异常终止