ios 如何在 Swift 中增加 Int 类型的成员变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27194344/
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
How to increment Int-typed member variable in Swift
提问by NumberOneRobot
I'm writing a Swift app and having trouble incrementing an Int type member variable.
我正在编写一个 Swift 应用程序并且在增加 Int 类型成员变量时遇到问题。
I created the variable with
我创建了变量
let index:Int
then in the initializer I instantiated it using
然后在初始化程序中我使用
self.index = 0
Later, when I try to increment it in a function using either of
后来,当我尝试使用以下任一方法在函数中增加它时
self.index++
or
或者
self.index = self.index + 1
I am told in the first case that "Cannot invoke '++' with argument of type 'Int'" and in the second case that "Cannot assign to 'pos' in 'self'".
我被告知在第一种情况下“无法使用类型为‘Int’的参数调用‘++’”,在第二种情况下“无法分配给‘self’中的‘pos’”。
I haven't been able to find information on the ++ operator, except that you can write custom versions of it, but I'd assume it's at least built in to the integer type. If that's not true then that answers that question.
我一直无法找到有关 ++ 运算符的信息,只是您可以编写它的自定义版本,但我认为它至少内置于整数类型中。如果这不是真的,那么这就回答了这个问题。
The other question I have no idea about.
另一个问题我不知道。
Thanks!
谢谢!
回答by Martin R
In
在
class MyClass {
let index : Int
init() {
index = 0
}
func foo() {
index++ // Not allowed
}
}
index
is a constantstored property. It can be given an initial value
index
是一个常量存储属性。可以给它一个初始值
let index : Int = 0
and can only be modified during initialization(And it must have a definite value when initialization is finished.)
并且只能在初始化时修改 (并且必须在初始化完成时有一个确定的值。)
If you want to change the value after its initialization then you'll have to declare it as a variablestored property:
如果要在初始化后更改该值,则必须将其声明为变量存储属性:
var index : Int
More information in "Properties"in the Swift documentation.
Swift 文档中“属性”中的更多信息。
Note that the ++
and --
are deprecated in Swift 2.2 and removed
in Swift 3 (as mentioned in a comment), so – if declared as a variable–
you increment it with
请注意,++
和--
在 Swift 2.2 中已弃用并在 Swift 3 中删除(如评论中所述),因此 - 如果声明为变量- 您可以使用
index += 1
instead.
反而。
回答by Max Haii
I think you can change
我觉得你可以改变
let index:Int
into
进入
var index:Int = 0
Because you are incrementing the value of index
, CHANGING its value, you need to declare it as a var
. Also, it's worthy of knowing that let
is used to declare a constant.
因为您正在增加 的值index
,更改其值,所以您需要将其声明为var
. 此外,值得知道的let
是用于声明常量。
Then, you can use self.index++
. Notice that there's no space in between self.index
and ++
.
然后,您可以使用self.index++
. 请注意,self.index
和之间没有空格++
。
Hope this will help.
希望这会有所帮助。