加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在Swift协议中为typealiases添加约束

发布时间:2020-12-14 04:26:44 所属栏目:百科 来源:网络整理
导读:我怎样才能指出B.Generator.Element应该是A? protocol SomeProtocol { typealias A typealias B: CollectionType func f(a: A) - B} 我意识到我可以做func f(node:B.Generator.Element) – B并完全消除A,但如果在某些其他协议中定义了A并且SomeProtocol继
我怎样才能指出B.Generator.Element应该是A?

protocol SomeProtocol {
    typealias A
    typealias B: CollectionType
    func f(a: A) -> B
}

我意识到我可以做func f(node:B.Generator.Element) – > B并完全消除A,但如果在某些其他协议中定义了A并且SomeProtocol继承了它,我就不能这样做.

编辑:

添加了示例

protocol P {
    typealias A
}

protocol Q: P {
    typealias B: CollectionType
    typealias A = B.Generator.Element
    func f(node: A) -> B
}

func g<A,T: Q where A == T.A>(arg1: T,arg2: A) {
    let collection = arg1.f(arg2)
    collection.contains(arg2) // Error here
}

编辑2:
为了澄清,我希望以某种方式在协议本身中指定A == B.Generator.Element,因为我必须使用自由函数.我在开发者论坛中找到了一个thread,正是我的问题.看起来它是当前类型系统的一个限制.我已经提交了一个雷达,让我们希望它得到解决:)

编辑3:
该问题已经存在雷达.提交时使用rdar:// 21420236.

解决方法

怎么样:

protocol SomeProtocol {
    typealias A = B.Generator.Element
    typealias B: CollectionType
    func f(a: A) -> B
}

编辑:

您得到的错误是因为无法保证A(B.Generator.Element)符合Equatable.因此,您无法在集合上调用contains,因为contains定义为:

extension SequenceType where Generator.Element : Equatable {
    public func contains(element: Self.Generator.Element) -> Bool
}

(我不确定为什么Xcode会提供包含作为一种有效的方法来调用,可能是一个错误……)

要解决这个问题,您可以:

// Since you're using Swift 2 you could use a protocol extension instead of a free function.

// Unfortunately,Xcode complains without the explicit declaration that `A` is 
// `B.Generator.Element`.
extension Q where A: Equatable,A == B.Generator.Element {
    func g(elem: A) {
        let collection = f(elem)
        collection.contains(elem)
        ...
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读