Swift协议扩展,实现具有共享关联类型的另一个协议 [英] Swift protocol extension implementing another protocol with shared associated type

查看:77
本文介绍了Swift协议扩展,实现具有共享关联类型的另一个协议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下内容:

protocol Foo {
  typealias A
  func hello() -> A
}
protocol FooBar: Foo {
  func hi() -> A
}
extension FooBar {
  func hello() -> A {
    return hi()
  }
}

class FooBarClass: FooBar {
  typealias A = String
  func hi() -> String {
    return "hello world"
  }
}

此代码进行编译.但是,如果我注释掉关联类型typealias A = String的显式定义,则由于某种原因,swiftc无法推断该类型.

This code compiles. But if I comment out explicit definition of associated type typealias A = String, then for some reason, swiftc fails to infer the type.

我感觉这与共享相同关联类型的两个协议有关,但没有通过类型参数化(例如,关联类型不够强大/不够成熟?)进行直接声明的情况,这使得类型推断变得模棱两可.

I'm sensing this has to do with two protocols sharing the same associated type but without a direct assertion through, for example, type parameterization (maybe associated type is not powerful/mature enough?), which makes it ambiguous for type inference.

我不确定这是否是该语言的错误/不成熟,或者也许我缺少协议扩展中的细微差别,这些细微差别会正确地导致这种行为.

I'm not sure if this is a bug / immaturity of the language, or maybe, I'm missing some nuances in protocol extension which rightfully lead to this behaviour.

有人可以阐明这一点吗?

Can someone shed some light on this?

推荐答案

看这个例子

protocol Foo {
    typealias A
    func hello() -> A
}
protocol FooBar: Foo {
    typealias B
    func hi() -> B
}
extension FooBar {
    func hello() -> B {
        return hi()
    }
}

class FooBarClass: FooBar {
    //typealias A = String
    func hi() -> String {
        return "hello world"
    }
}

使用泛型

class FooBarClass<T>: FooBar {
    var t: T?
    func hi() -> T? {
        return t
    }
}

let fbc: FooBarClass<Int> = FooBarClass()
fbc.t = 10
fbc.hello() // 10
fbc.hi()    // 10

这篇关于Swift协议扩展,实现具有共享关联类型的另一个协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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