首页 > 解决方案 > 无论其参数如何,从枚举数组中删除枚举

问题描述

我有一个枚举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函数说:

“BulletinOption”类型的表达式模式与“BulletinOption”类型的值不匹配

对于该行:

if case item = $0

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

成员“enableNotifications”需要“(eventId:String)”类型的参数

我只想删除那个枚举,不管它的论点是什么。我怎样才能做到这一点?

标签: swiftenums

解决方案


目前这是不可能的。

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

枚举案例模式匹配现有枚举类型的案例。枚举案例模式出现在switch语句案例标签以及、、和语句的case条件中。ifwhileguardfor-in

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

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

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

推荐阅读