【问题标题】:How can you case-match on a function/closure stored in a variable?如何对存储在变量中的函数/闭包进行大小写匹配?
【发布时间】:2018-03-11 17:19:50
【问题描述】:

考虑这段代码:

func testA(){}
func testB(value:Int){}
func testC(value:String){}

var someTest:Any = testA

如何对持有闭包的变量进行大小写匹配以找到正确的闭包以便调用它?

switch someTest{
    case let test where test:() -> Void:
        test()
    case let test where test:(value:Int) -> Void:
        test(4)
    case let test where test:(value:String) -> Void:
        test("A")
}

这样的事情可能吗?

【问题讨论】:

  • 你想要例如case let test as (String) -> Void,比较stackoverflow.com/q/38980403/2976878
  • 尽管根据您的用例,您可能需要考虑使用 enum 与每个函数类型的关联值;那么您可以彻底切换而无需进行类型转换。
  • @Alexander:问答不包括与闭包的匹配,我想知道这是否值得单独回答(由于他最初的评论,最好来自 Hamish)
  • 呃!因为不是在哪里。当然! Hamish,将其发布为答案,我会接受。
  • 哈哈是的,我做到了,公平地说,我会重新打开

标签: swift pattern-matching


【解决方案1】:

闭包类型与任何其他类型的切换模式相同:

switch someClosure {
    case let runnable as () -> Void:
        runnable()
    case let intConsumer as (Int) -> Void:
        intConsumer(4)
    case let stringConsumer as (String) -> Void:
        stringConsumer("A")
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多