xcode 在 Swift 中定义只读属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38318117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Define a read-only property in Swift
提问by Jason
How do you define a read-only property in Swift? I have one parent class which needs to define a public property eg. itemCount
. Here's my code:
你如何在 Swift 中定义只读属性?我有一个需要定义公共属性的父类,例如。itemCount
. 这是我的代码:
Class Parent: UIView {
private(set) var itemCount: Int = 0
}
class Child {
private(set) override var itemCount {
get {
return items.count
}
}
}
I get the error: Cannot override mutable property with read-only property
我收到错误: Cannot override mutable property with read-only property
Option 1 - Protocols:
选项 1 - 协议:
Well I can't use a protocol because they can't inherit from classes (UIView
)
好吧,我不能使用协议,因为它们不能从类 ( UIView
)继承
Option 2 - Composition:
选项 2 - 组成:
I add a var view = UIView
to my Child class and drop the UIView
inheritance from my Parent
class. This seems to be the only possible way, but in my actual project it seems like the wrong thing to do, eg. addSubview(myCustomView.view)
我将 a 添加var view = UIView
到我的 Child 类并UIView
从我的Parent
类中删除继承。这似乎是唯一可能的方法,但在我的实际项目中,这似乎是错误的做法,例如。addSubview(myCustomView.view)
Option 3 - Subclass UIView
on the Child
class
选择3 -子类UIView
的Child
类
I can't do this either because I intend to have multiple related Child
classes with different properties and behaviour, and I need to be able to declare instances of my Child
classes as the Parent
class to take advantage of UIView
's properties and Parent
's public properties.
我不能这样做,因为我打算拥有多个Child
具有不同属性和行为的相关类,并且我需要能够将我的Child
类的实例声明为Parent
类以利用UIView
的属性和Parent
公共属性。
采纳答案by Luca Angeletti
You can use a Computed Property
which (like a method) can be overridden.
您可以使用Computed Property
可以覆盖的which(如方法)。
class Parent: UIView {
var itemCount: Int { return 0 }
}
class Child: Parent {
override var itemCount: Int { return 1 }
}
Update (as reply to the comment below)
更新(作为对下面评论的回复)
This is how you declared and override a function
这就是您声明和覆盖函数的方式
class Parent: UIView {
func doSomething() { print("Hello") }
}
class Child: Parent {
override func doSomething() { print("Hello world!") }
}
回答by Tina
回答by invoodoo
As one more option you can use private variable for read/write and another for read-only. Count you're using for internal class changes, and numberOfItems for public access. Little bit weird, but it solves the problem.
作为另一种选择,您可以将私有变量用于读/写,而另一个用于只读。计算您用于内部类更改的计数,以及用于公共访问的 numberOfItems。有点奇怪,但它解决了问题。
class someClass {
private var count: Int = 0
var numberOfItems: Int { return count }
func doSomething() {
count += 1
}
}