我正在尝试用新的 Apple Swift 语言找出一些东西。假设我曾经在 Objective-C 中做过类似的事情。我有 readonly
属性,它们不能单独更改。但是,使用特定的方法,属性会以一种合乎逻辑的方式进行更改。
我举个例子,一个很简单的时钟。我会用Objective-C写这个。
@interface Clock : NSObject
@property (readonly) NSUInteger hours;
@property (readonly) NSUInteger minutes;
@property (readonly) NSUInteger seconds;
- (void)incrementSeconds;
@end
@implementation Clock
- (void)incrementSeconds {
_seconds++;
if (_seconds == 60) {
_seconds = 0;
_minutes++;
if (_minutes == 60) {
_minutes = 0;
_hours++;
}
}
}
@end
出于特定目的,我们不能直接触摸秒、分和小时,只能使用方法逐秒递增。只有这种方法可以利用实例变量的技巧来改变值。
由于 Swift 中没有这样的东西,我试图找到一个等价物。如果我这样做:
class Clock : NSObject {
var hours: UInt = 0
var minutes: UInt = 0
var seconds: UInt = 0
func incrementSeconds() {
self.seconds++
if self.seconds == 60 {
self.seconds = 0
self.minutes++
if self.minutes == 60 {
self.minutes = 0
self.hours++
}
}
}
}
这可行,但任何人都可以直接更改属性。
也许我在 Objective-C 中已经有一个糟糕的设计,这就是为什么潜在的新 Swift 等价物没有意义。如果没有,如果有人有答案,我将非常感激;)
也许苹果 promise 的 future 访问控制机制就是答案?
谢谢!
最佳答案
只需在属性声明前加上 private(set)
,如下所示:
public private(set) var hours: UInt = 0
public private(set) var minutes: UInt = 0
public private(set) var seconds: UInt = 0
private
将其保存在源文件的本地,而 internal
将其保存在模块/项目的本地。
private(set)
创建一个 read-only
属性,而 private
设置 set
和 获取
私有(private)。
https://stackoverflow.com/questions/24081194/
相关文章:
iphone - Objective C 从字符串中解析整数
objective-c - 如何在 Objective-C 中转换对象
ios - NSLocalizedString() 的第二个参数是什么?
objective-c - "Receiver type ' CALayer' 例如消息是前向声明”
ios - 如何将 NSAppTransportSecurity 添加到我的 info.plist
objective-c - 在 Objective-C 中将 NSNumber 转换为 int