【问题标题】:How to declare protocol constrainted generic variable in Swift?如何在 Swift 中声明协议约束的泛型变量?
【发布时间】:2016-07-25 18:19:14
【问题描述】:

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

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

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

我需要它,因为我可以创建带有签名的func

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

我想从Dictionary 获取param 参数的值,而不需要类型转换。

【问题讨论】:

    标签: swift generics nsmutabledictionary swift-dictionary


    【解决方案1】:

    简答

    在 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!
    

    对你有帮助吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-31
      • 1970-01-01
      • 1970-01-01
      • 2020-10-26
      • 2018-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多