专门用于通用协议的Swift协议 [英] Swift protocol specializing generic protocol

查看:102
本文介绍了专门用于通用协议的Swift协议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以有专门用于通用协议的协议?我想要这样的东西:

Is it possible to have a protocol that specializes a generic protocol? I want something like this:

protocol Protocol: RawRepresentable {
  typealias RawValue = Int
  ...
}

这确实可以编译,但是当我尝试从Protocol实例访问initrawValue时,其类型为RawValue而不是Int.

This does compile, but when I try to access the init or rawValue from a Protocol instance, its type is RawValue instead of Int.

推荐答案

在Swift 4中,您可以向协议添加约束:

In Swift 4, you can add constraints to your protocol:

protocol MyProtocol: RawRepresentable where RawValue == Int {
}

现在,在MyProtocol上定义的所有方法都将具有Int rawValue.例如:

And now all methods defined on MyProtocol will have an Int rawValue. For example:

extension MyProtocol {
    var asInt: Int {
        return rawValue
    }
}

enum Number: Int, MyProtocol {
    case zero
    case one
    case two
}

print(Number.one.asInt)
// prints 1

采用RawRepresentable但RawValue不是Int的类型不能采用您的约束协议:

Types that adopt RawRepresentable but whose RawValue is not Int can not adopt your constrained protocol:

enum Names: String {
    case arthur
    case barbara
    case craig
}

// Compiler error
extension Names : MyProtocol { }

这篇关于专门用于通用协议的Swift协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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