【问题标题】:Define a read-only property in Swift在 Swift 中定义一个只读属性
【发布时间】:2016-07-12 00:17:08
【问题描述】:

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

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

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

我收到错误:Cannot override mutable property with read-only property


选项 1 - 协议:

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

选项 2 - 组成:

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

选项 3 - Child 类的子类 UIView

我也不能这样做,因为我打算拥有多个具有不同属性和行为的相关 Child 类,并且我需要能够将我的 Child 类的实例声明为要采用的 ParentUIView 的属性和Parent 的公共属性的优势。

【问题讨论】:

    标签: ios swift xcode uiview xcode8


    【解决方案1】:

    您可以使用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!") }
    }
    

    【讨论】:

    • 谢谢!我是否也必须使用varoverride var 来声明函数?
    • 不,declare a function 你使用func 关键字。
    • 我无法在Parent 中定义它,并且无法在Child 类中成功覆盖它
    【解决方案2】:

    您可以将 setter 声明为私有,而 getter 是公开的。

    public class someClass {
        public private(set) var count: String
    }
    

    参考这个link

    【讨论】:

    • 链接已失效。 :(
    【解决方案3】:

    作为另一种选择,您可以将私有变量用于读/写,另一个用于只读。计数用于内部类更改,numberOfItems 用于公共访问。有点奇怪,但它解决了问题。

    class someClass {
        private var count: Int = 0
        var numberOfItems: Int { return count }
    
        func doSomething()  {
           count += 1
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-12-07
      • 2010-11-14
      • 2014-11-20
      • 1970-01-01
      • 2015-11-09
      • 2016-09-20
      • 2017-06-06
      相关资源
      最近更新 更多