【问题标题】:Workaround/resolution for Swift compiler error related to Void callback defined in struct与 struct 中定义的 Void 回调相关的 Swift 编译器错误的解决方法/解决方案
【发布时间】:2015-08-14 03:54:17
【问题描述】:

由于 Swift 中的typealias 定义缺乏泛型支持,我编写了一个泛型的ResultHandler<T> 回调,如下所示:

struct ResultHandler<T> {
    let f: (result: T) -> ()
}

这对于使用除Void 以外的任何内容的处理程序非常有用:

Dispatch<Bool>.dispatch({ () -> (Result<Bool>) in
    Result<Bool>(true)
}).onResult(ResultHandler() { (result: Bool) in
    if result {
        self.doSomething() // Method executes successfully
    }
})

但是当尝试使用Void:

Dispatch<Void>.dispatch({ () -> (Result<Void>) in
    Result<Void>()
}).onResult(ResultHandler() { (result: Void) in // Compiler error here
    self.doSomething()
})

出现编译错误:

函数签名 '(Void) -> ()' 与预期类型不兼容 '(结果:无效)->()'

这似乎误导/编译器错误,好像我将签名更改为使用错误类型的值:

Dispatch<Void>.dispatch({ () -> (Result<Void>) in
    Result<Void>()
}).onResult(ResultHandler() { (result: Void?) in // Compiler error here
    self.doSomething()
})

错误消息选择了可选指示?,但仍然无法正确检测到我的result: 标签:

函数签名 '(Void?) -> ()' 与预期类型不兼容 '(结果:无效)->()'

我做错了什么?

【问题讨论】:

    标签: xcode swift generics


    【解决方案1】:

    您不需要在闭包类型声明中指定参数名称——这就是给编译器带来问题的原因:

    struct ResultHandler<T> {
        let f: T -> ()
    }
    

    现在您可以创建使用 Bool 参数、Void 参数或完全省略参数的 ResultHandler 实例:

    let r1 = ResultHandler() { (result: Bool) in
        if result {
            // do something
        }
    }
    
    let r2 = ResultHandler() { (_: Void) in
        // do something
    }
    
    let r3 = ResultHandler() {
        // do something
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多