3

How do I change a specific associated value of an enum

enum Origin {
    case search(searchTerm: String, filtered: Bool)
    case category(categoryName:String, subcategoryName:String)

}

@objc class GameSession: NSObject
{
    var gameOrigin: Origin?

    ...

    @objc func setIsSearchFiltered(filtered:Bool)
    {
        if (<gameOrigin is of type .search?>)
        {
            self.gameOrigin = <change "filtered" associated value to new value>
        }
    }

    ....
}

This question with answer, unfortunately, lately didn't help me.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Luda
  • 7,282
  • 12
  • 79
  • 139
  • @Luda can you show the actual code for assigning/updating the `gameOrigin`? – Kamran Sep 27 '18 at 11:45
  • @Kamran, this is what I am looking for – Luda Sep 27 '18 at 11:57
  • @MartinR Can you please write down how would you do it? The new enum value should have the same associated values except of "filtered" – Luda Sep 27 '18 at 11:59
  • @MartinR C What worked was case .search(let searchTerm, _): gameOrigin = .search(searchTerm: searchTerm, filtered: filtered). You can put this as an answer. By the way, is there a way to use if instead of case? – Luda Sep 27 '18 at 13:02

2 Answers2

5

You can only assign a new enumeration value to the variable. As in Can I change the Associated values of a enum?, the associated values of the current values can be retrieved in a switch statement, with a case pattern which binds the associated value to a local variable.

The currently associated filtered value is not needed, therefore we can use a wildcard pattern _ at that position.

Since var gameOrigin: Origin? is an optional, we need an “optional pattern” with a trailing question mark.

switch gameOrigin {
case .search(let searchTerm, _)?:
    gameOrigin = .search(searchTerm: searchTerm, filtered: filtered)
default:
    break
}

The same can be done also in an if-statement with case and pattern matching:

if case .search(let searchTerm, _)? = gameOrigin {
    gameOrigin = .search(searchTerm: searchTerm, filtered: filtered)
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
0

Swift change Enum associated value

[Swift Enum]

One more example with mutating[About] function

enum Section {
    case info(header: String)
    
    mutating func change(newHeader: String) {
        switch self {
        case .info(let header):
            self = .info(header: "\(header) \(newHeader)")
        }
    }
}

//changing
var mySection = Section.info(header: "Hello world")
mySection.change(newHeader: "And Peace")

//printing
switch mySection {
case .info(let header):
    print(header) //"Hello world And Peace"
}
yoAlex5
  • 29,217
  • 8
  • 193
  • 205