简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM