我可以更改枚举的关联值吗? [英] Can I change the Associated values of a enum?

查看:54
本文介绍了我可以更改枚举的关联值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Swift浏览文档,并且遇到了问题。
这是代码:

I am reading the Swift tour document, and facing a problem. Here is the code:

enum SimpleEnum {
    case big(String)
    case small(String)
    case same(String)

    func adjust() {
        switch self {
        case let .big(name):
            name +=  "not"
        case let .small(name):
            name +=  "not"
        case let .same(name):
            name +=  "not"
        }
    }
}

函数 adjust()不起作用,我想知道是否有办法更改枚举的关联值,以及如何更改?

The function adjust() won't work, I wonder if there is a way to change the Associated value of an enum, and how?

推荐答案

您最直接的问题是,当您尝试更改不可变变量(用 let 声明)的值时,用 var 声明它。但是,由于您的名称变量包含关联值的副本,因此,这不能解决该特定问题,但是一般而言,您需要注意这一点。

Your most immediate problem is that you're attempting to change the value of an immutable variable (declared with let) when you should be declaring it with var. This won't solve this particular problem though since your name variable contains a copy of the associated value, but in general this is something that you need to be aware of.

如果要解决此问题,则需要将 adjust()函数声明为变异函数并重新分配self视具体情况而定,是一个新的枚举值,其关联值由旧值和新值组成。例如:

If you want to solve this, you need to declare the adjust() function as a mutating function and reassign self on a case by case basis to be a new enum value with an associated value composed from the old one and the new one. For example:

enum SimpleEnum{
    case big(String)
    case small(String)
    case same(String)

    mutating func adjust() {
        switch self{
        case let .big(name):
            self = .big(name + "not")
        case let .small(name):
            self = .small(name + "not")
        case let .same(name):
            self = .same(name + "not")
        }
    }
}

var test = SimpleEnum.big("initial")
test.adjust()

switch test {
case let .big(name):
    print(name) // prints "initialnot"
case let .small(name):
    print(name)
case let .same(name):
    print(name)
}

这篇关于我可以更改枚举的关联值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆