swift - 从枚举数组中删除枚举,无论其参数如何

标签 swift enums

我有一个枚举BulletinOptions:

enum BulletinOption {
    case notificationPermissions
    case enableNotifications(eventId: String)
    case join(hostName: String, eventId: String)
    case share(type: SocialBulletinItem.BulletinType.Social, event: EventJSONModel, view: UIView)
    case completedShare(type: SocialBulletinPageItem.SocialButtonType)
}

我有一个这样的枚举数组:

let array = [
    .join(hostName: hostName, eventId: event.id),
    .notificationPermissions,
    .enableNotifications(eventId: event.id),
    .share(type: .queue(position: 0, hostName: ""), event: event, view: view)
]

我想创建一个可以从此数组中删除特定枚举的函数。我有这段代码:

func remove(
    item: BulletinOption,
    from options: [BulletinOption]) -> [BulletinOption] {
    var options = options

    if let index = options.firstIndex(where: {
        if case item = $0 {
            return true
        }
        return false
    }) {
        options.remove(at: index)
    }

    return options
}

我想做的是:

let options = remove(item: .enableNotifications, from: options)

但是,这给了我两个错误。 remove 函数说:

Expression pattern of type 'BulletinOption' cannot match values of type 'BulletinOption'

对于行:

if case item = $0

第二个错误是在调用该函数时:

Member 'enableNotifications' expects argument of type '(eventId: String)'

我只想删除那个枚举,不管它的参数是什么。我该怎么做?

最佳答案

目前这是不可能的。

您要做的实际上是将枚举案例模式作为参数传递给方法,以便该方法可以将数组中的每个值与该模式相匹配。然而,swift guide说:

An enumeration case pattern matches a case of an existing enumeration type. Enumeration case patterns appear in switch statement case labels and in the case conditions of if, while, guard, and for-in statements.

这意味着枚举案例模式不允许作为函数的参数。 :(

所以你能做的最好的就是:

array.filter {
    if case .enableNotifications = $0 { return false } else { return true }
}

关于swift - 从枚举数组中删除枚举,无论其参数如何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56481650/

相关文章:

swift - 在 Linux 上使用 Swift 生成随机数时出错?

ios - 检查两个对象在 Swift 中是否为 nil,ios xcode

swift - 如何将电话号码返回到 swift 应用程序?

javascript - 如何循环枚举值以在单选按钮中显示?

c - 头文件中的枚举声明

c++ - 如何将枚举值分配给用户定义的 double 变量?? C++

java - 具有切换选项的功能

c# - 枚举.TryParse : Is there a guarantee or contract for the out parameter value when the return value is `false` ?

swift - 如何使用 Swift 2.3 和 3.0 编译模块?

ios - UIDevice currentDevice 模型可能的值