Swift中的只读和非计算变量属性 [英] Read-only and non-computed variable properties in Swift

查看:98
本文介绍了Swift中的只读和非计算变量属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用新的Apple Swift语言解决问题.假设我以前在Objective-C中执行以下操作.我具有readonly属性,不能单独更改它们.但是,使用一种特定的方法,可以按照逻辑方式更改属性.

I'm trying to figure out something with the new Apple Swift language. Let's say I used to do something like the following in Objective-C. I have readonly properties, and they cannot be individually changed. However, using a specific method, the properties are changed in a logical way.

我举一个下面的例子,一个非常简单的时钟.我将在Objective-C中编写该代码.

I take the following example, a very simple clock. I would write this in 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

出于特定目的,我们不能直接触摸秒,分钟和小时,而只能使用一种方法逐秒递增.只有这种方法才能使用实例变量的技巧来更改值.

For a specific purpose, we cannot touch the seconds, minutes and hours directly, and it's only allowed to increment second by second using a method. Only this method could change the values by using the trick of the instance variables.

由于Swift中没有这样的东西,所以我试图找到一个等效的东西.如果我这样做:

Since there are no such things in Swift, I'm trying to find an equivalent. If I do this:

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++
            }
        }
    }
}

那行得通,但是任何人都可以直接更改属性.

That would work, but anybody could change directly the properties.

也许我已经在Objective-C中设计不好,这就是为什么潜在的新Swift替代物没有意义的原因.如果没有,如果有人回答,我将不胜感激;)

Maybe I already had a bad design in Objective-C and that's why the potential new Swift equivalent is not making sense. If not and if someone have an answer, I would be very grateful ;)

也许苹果承诺的未来访问控制机制是答案?

Maybe the future Access Control Mechanisms promised by Apple is the answer?

谢谢!

推荐答案

private(set)简单地在属性声明前添加前缀,就像这样:

Simply prefix the property declaration with private(set), like so:

public private(set) var hours:   UInt = 0
public private(set) var minutes: UInt = 0
public private(set) var seconds: UInt = 0

private将其保留在源文件本地,而internal将其保留在模块/项目本地.

private keeps it local to a source file, while internal keeps it local to the module/project.

private(set)创建一个read-only属性,而privatesetget都设置为私有.

private(set) creates a read-only property, while private sets both, set and get to private.

这篇关于Swift中的只读和非计算变量属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆