更改枚举Swift的关联值 [英] Changing associated value of enum Swift

查看:220
本文介绍了更改枚举Swift的关联值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何更改枚举的特定关联值

 枚举Origin {
case search(searchTerm:字符串,已过滤:Bool)
案例类别(categoryName:字符串,subcategoryName:String)

}

@objc类GameSession:NSObject
{
var gameOrigin:起源?

...

@objc func setIsSearchFiltered(filtered:Bool)
{
if(< gameOrigin类型为.search?> )
{
self.gameOrigin =<将已过滤的关联值更改为新值>
}
}

....
}

这个有答案的问题,很遗憾,最近对我没有帮助。

解决方案

您只能分配该变量的新枚举值。
我可以更改枚举的关联值?
当前值的关联值可以在switch语句
中使用case样式将关联值绑定到局部变量。 p>

不需要当前关联的过滤的值,因此
我们可以使用通配符模式 _



由于 var gameOrigin:Origin?是可选,我们需要带有尾随问号的可选模式。

  switch gameOrigin {
case .search(让searchTerm,_)?:
gameOrigin = .search(searchTerm:searchTerm,已过滤:已过滤)
默认值:
break
}

在具有情况和模式$ b $的if语句中,也可以这样做b匹配:

 如果是case.search(让searchTerm,_)? = gameOrigin {
gameOrigin = .search(searchTerm:searchTerm,已过滤:已过滤)
}


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的关联值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆