我有一个枚举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 thecase
conditions ofif
,while
,guard
, andfor-in
statements.
这意味着枚举案例模式不允许作为函数的参数。 :(
所以你能做的最好的就是:
array.filter {
if case .enableNotifications = $0 { return false } else { return true }
}
关于swift - 从枚举数组中删除枚举,无论其参数如何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56481650/