我在斯威夫特有个谜:
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),但在这种情况下,必须将返回值显式地分配回枚举变量,这对我来说就像是糟糕的编码。似乎更有用的是说myOrientation.rotate(),并让值隐式地改变。
这个问题有什么好的解决办法吗?
谢谢你们!
发布于 2014-11-18 03:43:58
当要修改方法中的值类型(即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之前打开它。如果正确地实现了先前的逻辑,那么使用强制展开操作符!应该是安全的。
https://stackoverflow.com/questions/26986003
复制相似问题