0

我需要创建一个字典变量,其中我的值将属于SomeOtherClass类并符合SomeProtocol. 这等于 Objective-C 中的以下声明:

NSMutableDictionary<SomeClass *, SomeOtherClass<SomeProtocol> *> *someOtherBySome;

那么,是否可以使用 Swift 以同样简单的方式做到这一点?

我需要它,因为我可以func使用签名创建:

func someFunc<T: SomeOtherClass where T: SomeProtocol>(param: T, otherParam: String)

我想在没有类型转换的情况下获取param参数的值。Dictionary

4

1 回答 1

2

简短的回答

在 Swift 中,你不能声明一个给定的变量class 并且符合一个protocol.

可能的解决方案(?)

但是,鉴于您已经拥有的定义

class SomeClass: Hashable {
    var hashValue: Int { return 0 } // your logic goes here
}

func ==(left:SomeClass, right:SomeClass) -> Bool {
    return true // your logic goes here
}

class SomeOtherClass {}
protocol SomeProtocol {}

SomeOtherClass也许你可以简单地解决你的问题SomeProtocol

extension SomeOtherClass: SomeProtocol { }

现在您可以简单地

var dict : [SomeClass: SomeOtherClass] = [SomeClass(): SomeOtherClass()]

let someProtocolValue: SomeProtocol = dict.values.first!

它对你有帮助吗?

于 2016-07-25T19:04:21.190 回答