【问题标题】:In Swift, how to extend a typealias?在 Swift 中,如何扩展类型别名?
【发布时间】:2016-02-19 16:13:05
【问题描述】:

我有一个类型别名:

typealias BeaconId = [String: NSObject]

我想通过以下方式扩展它:

extension BeaconId {}

但这会引发编译错误:

约束扩展必须在非特化泛型类型“字典”上声明,约束由“where”子句指定

所以我最终做了:

extension Dictionary where Key: StringLiteralConvertible, Value: NSObject {}

有没有更清洁的方法来做到这一点?

【问题讨论】:

  • 我试图清理你的代码,实际上得到了这个错误:constrained extension must be declared on the unspecialized generic type 'Dictionary' with constraints specified by a 'where' clause
  • 是的,我也明白了,您可以在下面查看我的完整答案。基本上它看起来不可能扩展指定的泛型类型,只有那些尚未设置泛型类型的类型。
  • @Robert 我希望在 Swift 3 中看到的不仅仅是对协议和继承的约束,还有对值的约束,例如 extension SomeEnum where Self == .MyCase。这样,功能只能在特定的枚举案例中定义。

标签: swift extend type-alias


【解决方案1】:

在 Swift 4.2 时更新: 您现在可以这样做了

例子:

typealias KeyedNumbers = [String: Int]

extension KeyedNumbers {
    func squaredValue(forKey key: String) -> Int {
        return self[key]! * self[key]!
    }
}

有了那个(相当没用的)扩展,你可以这样做:

let pairs = ["two": 2, "three": 3]
print("2 squared =", pairs.squaredValue(forKey: "two"))

它会打印出来

2 平方 = 4

【讨论】:

    【解决方案2】:

    AFAIK,不。

    考虑以下示例:

    typealias Height: Float
    
    extension: Height {
    
    }
    

    这里的Height 不是一个新类型,它只是Float 的一个标签,所以你只是在扩展Float。如果您查看Dictionary 它是public struct Dictionary<Key : Hashable, Value> : CollectionType, DictionaryLiteralConvertible,那么您将尝试实现的目标

    extension BeaconID {}
    

    正在为 Dictionary 添加带有特定通用参数的扩展。

    我希望你应该能够做的是:

    typealias BeaconID = Dictionary<Key: String, Value: NSObject>
    

    但这也不能编译,这是因为在 Swift 中你不能为部分类型键入别名(换句话说,没有特定泛型参数类型的泛型类型。有关更多信息,请参阅here)。类型别名泛型类型的一种可能的解决方法,在我链接到的答案下方注明是

    struct Wrapper<Key: Hashable, Value> {
        typealias T = Dictionary<Key, Value>
    }
    typealias BeaconID = Wrapper<String, NSObject>.T
    

    但即便如此,当您尝试扩展 BeaconID 时,您也会收到编译器警告,这最终触及了问题的核心:

    “约束扩展必须在非特化泛型类型‘字典’上声明,约束由‘where’子句指定”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-24
      • 1970-01-01
      • 2016-08-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多