与数组匹配的 Swift 开关模式 [英] Swift switch pattern matching with arrays

查看:42
本文介绍了与数组匹配的 Swift 开关模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好奇是否有办法在 Swift 中执行以下操作.

Curious if there is a way to do the following in Swift.

let foo = [1, 2, 3]
let bar = [4, 5, 6]

let value = 5

switch value {
case in foo
    print("5 is in foo")
case in bar
    print("5 is in bar")
default:
    break
}

我知道还有其他方法可以使这个人为的示例工作,例如 case 4, 5, 6: 或不使用开关而是使用 bar.contains(value) 但我正在寻找一种解决方案,专门涉及将开关模式匹配到数组.谢谢!

I understand there are other ways I could make this contrived example work such as case 4, 5, 6: or not using a switch and instead using bar.contains(value) but I'm looking for a solution specifically involving switch pattern matching to an array. Thanks!

推荐答案

您可以定义自定义模式匹配运算符~= 接受一个数组作为模式"和一个值:

You could define a custom pattern matching operator ~= which takes an array as the "pattern" and a value:

func ~=<T : Equatable>(array: [T], value: T) -> Bool {
    return array.contains(value)
}

let foo = [1, 2, 3]
let bar = [4, 5, 6]

let value = 5

switch value {
case foo:
    print("\(value) is in foo")
case bar:
    print("\(value) is in bar")
default:
    break
}

类似的运营商已经存在,例如对于间隔:

Similar operators exist already e.g. for intervals:

public func ~=<I : IntervalType>(pattern: I, value: I.Bound) -> Bool

这篇关于与数组匹配的 Swift 开关模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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