首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是否有可能从枚举方法中更改枚举?

是否有可能从枚举方法中更改枚举?
EN

Stack Overflow用户
提问于 2014-11-18 03:17:15
回答 1查看 836关注 0票数 2

我在斯威夫特有个谜:

代码语言:javascript
复制
enum Orientation: Int
{
    case Rot_0 = 0, Rot_90, Rot_180, Rot_270

和非静态的方法,在我的枚举设计,以改变方向顺时针或逆时针方向:

代码语言:javascript
复制
    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(),并让值隐式地改变。

这个问题有什么好的解决办法吗?

谢谢你们!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-11-18 03:43:58

当要修改方法中的值类型(即structenum)时,需要将其标记为mutating。这将使该方法可用于可变实例(用var ...声明),而不是不可变实例(let ...):

代码语言:javascript
复制
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之前打开它。如果正确地实现了先前的逻辑,那么使用强制展开操作符!应该是安全的。

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26986003

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档