Changing associated value of enum Swift

十年热恋 提交于 2020-02-25 04:05:53

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/52535970/changing-associated-value-of-enum-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!