Q:

Changing associated value of enum Swift

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.

A:

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

