我在Swift中有一个枚举:
enum Orientation: Int
{
case Rot_0 = 0, Rot_90, Rot_180, Rot_270
和我的枚举中的一种非静态方法,该方法旨在顺时针或逆时针移动方向:
func rotate(clockwise: Bool)
{
var nextRawValue = self.rawValue + (clockwise ? 1 : -1)
if nextRawValue < Orientation.Rot_0.rawValue
{
nextRawValue = Orientation.Rot_270.rawValue
}
else if nextRawValue > Orientation.Rot_270.rawValue
{
nextRawValue = Orientation.Rot_0.rawValue
}
self = Orientation(rawValue: nextRawValue)
}
编译器告诉我您不能self
在方法中分配给它。我无法理解为什么这是不可能的。
我唯一想到的就是拥有一个静态方法rotate(orientation: Orientation, clockwise: Bool)
,但是在这种情况下,必须将返回值显式分配回enum变量,这对我来说就像是不好的编码。说出来myOrientation.rotate()
并隐式更改值似乎更有用。
有没有解决这个问题的好方法?
谢谢你们!
当您要在方法中修改值类型(即struct
或enum
)时,需要将其标记为mutating
。这将使该方法可用于可变实例(用声明var ...
),但不能用于不可变实例(let ...
):
mutating func rotate(clockwise: Bool)
{
var nextRawValue = self.rawValue + (clockwise ? 1 : -1)
if nextRawValue < Orientation.Rot_0.rawValue
{
nextRawValue = Orientation.Rot_270.rawValue
}
else if nextRawValue > Orientation.Rot_270.rawValue
{
nextRawValue = Orientation.Rot_0.rawValue
}
self = Orientation(rawValue: nextRawValue)!
}
请注意,解决变异错误会揭示另一个错误-Orientation(rawValue: nextRawValue)
返回一个可选参数,因此您需要先将其展开,然后才能分配给self
。如果正确实现了先前的逻辑,则应该安全地使用force unwrapping运算符!
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句