我的情况是我有一个包含 associatedtype
的自定义类型。在这等于 Void
的情况下,我希望有一些默认行为(以使调用站点更方便)。我试图将示例归结为:
protocol FooType {
associatedtype T: Any
var bar: (String) -> T { get }
}
struct Foo<T>: FooType {
let bar: (String) -> T
}
extension Foo where T == Void { // Compile error: "Same-type requirement makes generic parameter 'T' non-generic".
init() {
self.bar = { _ in return }
}
}
想法是,在泛型类型为 Void
的情况下,(在我的场景中)传入函数(名为 bar
在示例中)。因此,我只想在这个特定的上下文中为这个函数提供一个默认实现。
当尝试执行上述操作时,我得到了 Same-type requirement makes generic parameter 'T' non-generic
这听起来与尝试限制时发生的情况非常相似,例如Array
类型(当包含特定类型时)。一个解决方法是引入一个协议(protocol),但我不能为 Void
这样做。是否可以做我想做的事,或者这是目前 Swift 3 的限制?
最佳答案
从 Swift 3.1 开始,问题中发布的代码现在可以使用了。也就是说,以下内容现在可以正常工作:
protocol FooType {
associatedtype T: Any
var bar: (String) -> T { get }
}
struct Foo<T>: FooType {
let bar: (String) -> T
}
extension Foo where T == Void {
init() {
self.bar = { _ in return }
}
}
let foo = Foo<String>(bar: { (t: String) in return "" })
let zoo = Foo<Void>()
关于swift - 扩展关联类型等于 Void 的自定义类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40283231/