隐式解包可选使不可变

时间:2014-06-06 22:48:30

标签: swift

为什么我不能改变一个隐式解包的可选变量?

以下是重现问题的简短示例:

使用数组

var list: [Int]! = [1]
list.append(10) // Error here

Immutable value of type '[Int]' only has mutating members named 'append'

使用Int

var number: Int! = 1
number = 2
number = 2 + number
number += 2 // Error here

Could not find an overload for '+=' that accepts the supplied arguments

2 个答案:

答案 0 :(得分:5)

因为你试图改变它们的方式是改变值(它们是不可变的)而不是改变var

在Swift中,值类型是不可变的。一直都是。

变异不是值的变异,它是包含该值的变量的变异。

对于Int+=运算符在左侧获取结构,在右侧获取Int,并且不能向int添加结构。

Array的情况下,append是变异成员。但它是在不直接存储在变量中的不可变值上调用的。它只能对直接存储在变量中的值进行操作(这使得它们变得可变:它们存储在变量中的事实。它们实际上不是可变的,变量是)。

答案 1 :(得分:4)

<强>更新

这已经在Xcode Beta 5中修复了一个小警告:

var list: [Int]! = [1]
list.append(10)

var number: Int! = 1
number! += 2
number += 2 // compile error

数组按预期工作,但现在似乎整数仍然需要显式展开以允许使用+=


目前,这只是Optionals的性质(无论是否隐式解包)。 unwrap运算符返回不可变值。 This is likely to be fixed or a better solution will be provided in the future

现在唯一的办法是将数组包装在一个类中:

class IntArray {
    var elements : [Int]
}
相关问题