隐式解包可选使不可变 [英] Implicitly unwrapped optional made immutable
问题描述
为什么我不能改变隐式解包的可选变量?
这是一个重现问题的简短示例:
带数组
变量列表:[Int]!= [1]list.append(10)//这里出错
'[Int]' 类型的不可变值只有名为 'append' 的可变成员
带整数
变量编号:整数!= 1数字 = 2数字 = 2 + 数字number += 2//这里有错误
找不到接受所提供参数的+="的重载
更新:
此问题已在 Xcode Beta 5 中修复,但有一个小警告:
变量列表:[Int]!= [1]list.append(10)变量编号:整数!= 1数字!+= 2number += 2//编译错误
数组按预期工作,但现在似乎整数仍然需要显式解包以允许使用 +=
目前,这只是 Optionals 的本质(无论是否隐式解包).unwrap 运算符返回一个不可变的值.这很可能会得到修复,或者将来会提供更好的解决方案.>
目前唯一的解决方法是将数组包装在一个类中:
class IntArray {无功元素:[Int]}
Why is it that I cannot mutate an implicitly unwrapped optional variable?
Here is a short example the reproduces the issue:
With Array
var list: [Int]! = [1]
list.append(10) // Error here
Immutable value of type '[Int]' only has mutating members named 'append'
With 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
Update:
This has been fixed in Xcode Beta 5 with one small caveat:
var list: [Int]! = [1]
list.append(10)
var number: Int! = 1
number! += 2
number += 2 // compile error
The array works as expected, but it seems that right now the integer still requires an explicit unwrap to allow using +=
Currently, this is just the nature of Optionals (whether implicitly unwrapped or not). The unwrap operator returns an immutable value. This is likely to be fixed or a better solution will be provided in the future.
The only way around it for now is to wrap the array in a class:
class IntArray {
var elements : [Int]
}
这篇关于隐式解包可选使不可变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!