Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
866 views
in Technique[技术] by (71.8m points)

swift - Can I change the Associated values of a enum?

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"
        }
    }
}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...