枚举模式匹配作为函数调用的参数 [英] Enum pattern matching as a parameter to a function call
问题描述
我已经建立了一个带示例的游乐场:
I've setup a playground with an example:
enum CarType : Equatable {
case wheeled(wheels: Int)
case flying
public static func ==(lhs: CarType, rhs: CarType) -> Bool {
return lhs.enumName == rhs.enumName
}
var enumName: String {
let stuff = "\(self)".split(separator: "(").first!
return String(describing: stuff)
}
}
var typesPresentAtMyParty = [CarType.wheeled(wheels:4), .wheeled(wheels:4), .flying]
let aKnownType = CarType.flying
if case aKnownType = typesPresentAtMyParty[2] {
print("Was the type")
}
func isPresent(type: CarType, inArray: [CarType]) -> Bool {
return inArray.filter {
if case type = $0 {
return true
}
return false
}.first != nil
}
func isWheeled(inArray: [CarType]) -> Bool {
return inArray.filter {
if case .wheeled = $0 {
return true
}
return false
}.first != nil
}
isPresent(type: .flying, inArray: typesPresentAtMyParty)
isPresent(type: .wheeled, inArray: typesPresentAtMyParty)
这里的最后一行不编译。虽然我可以执行如果case .wheeled = $ 0
忽略关联类型作为检查,但是我找不到在函数调用 isPresent中执行相同操作的方法(类型:CarType,inArray:[CarType])
,当发送 isPresent(类型:.wheeled,inArray:typesPresentAtMyParty)
The last line here does not compile. While i can do if case .wheeled = $0
ignoring associated type as a check, i cannot find a way of doing the same in a function call isPresent(type: CarType, inArray: [CarType])
, when sending isPresent(type: .wheeled, inArray: typesPresentAtMyParty)
有没有一种方法可以编写只将枚举的有效模式匹配部分作为参数的函数?
Is there a way of writing a function that takes only the valid pattern matching part of the enum as a parameter?
推荐答案
不可能将部分构造的枚举传递给函数。部分构造的枚举不是有效值,它们仅在模式匹配中起作用,因为编译器有一个具体的值可使用-模式右侧的值。
It is not possible to pass partially constructed enums to a function. Partially constructed enums are not valid values, and they only work in pattern matching because the compiler has a concrete value to work with - the one from the right side of the pattern.
话虽这么说,您可以轻松地将函数重写为更好,更快捷的版本。
These being said, you could easily rewrite your functions to better, more swiftier versions.
首先,您不需要 isPresent
,您只需使用以下内容即可:
Firstly, you don't need isPresent
, you can simply use contains:
typesPresentAtMyParty.contains { $0 == .flying }
typesPresentAtMyParty.contains { if case . wheeled = $0 { return true } else { return false } }
类似地, isWheeled
可以缩短(并重新命名,以获取更好的语义):
Similarly, isWheeled
can be shortened (and renamed, for better semantics):
func isWheeled(_ carType: CarType) -> Bool {
if case . wheeled = carType { return true } else { return false }
}
可以通过到包含
:
let hasWeeled = typesPresentAtMyParty.contains(where: isWheeled)
这篇关于枚举模式匹配作为函数调用的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!