swift - 扩展关联类型等于 Void 的自定义类型

标签 swift generics swift3 protocols protocol-extension

我的情况是我有一个包含 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/

相关文章:

c# - 通用类型、集合和对象引用

java - 在接口(interface)扩展中指定泛型

ios - 为什么从未执行过的 Swift 3 代码会抛出运行时错误?

ios 快速改变方向将改变 UIView 设计

ios - Swift - 协议(protocol)扩展 - 属性默认值

ios - 以编程方式添加前导/顶部约束

c# - 如何从 C# 中的泛型方法返回 NULL?

ios - 如何禁用 UITabBarController 中的选项卡?

ios - UIScrollView 内的 UIViewControllers 内的 UIbutton 不会在触摸时触发

ios - 是否可以使用 swift 将用户输入输出到 .csv?