在Swift中,如何扩展typealias?

gup*_*ron 12 extend type-alias swift

我有一个typealias:

typealias BeaconId = [String: NSObject]
Run Code Online (Sandbox Code Playgroud)

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

extension BeaconId {}
Run Code Online (Sandbox Code Playgroud)

但这会引发编译错误:

必须在非专用泛型类型'Dictionary'上声明约束扩展,并使用'where'子句指定约束

所以我最终做到了:

extension Dictionary where Key: StringLiteralConvertible, Value: NSObject {}
Run Code Online (Sandbox Code Playgroud)

有更清洁的方法吗?

epo*_*gee 5

Swift 4.2时更新: 您现在可以执行此操作

例:

typealias KeyedNumbers = [String: Int]

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

有了适当的扩展(几乎没有用),您可以执行以下操作:

let pairs = ["two": 2, "three": 3]
print("2 squared =", pairs.squaredValue(forKey: "two"))
Run Code Online (Sandbox Code Playgroud)

它会打印

2平方= 4


bar*_*dog 4

据我所知,不。

考虑以下示例:

typealias Height: Float

extension: Height {

}
Run Code Online (Sandbox Code Playgroud)

Height不是一个新类型,它只是一个标签,Float所以你只是扩展Float. 如果你看一下,Dictionarypublic struct Dictionary<Key : Hashable, Value> : CollectionType, DictionaryLiteralConvertible就是你想要实现的目标

extension BeaconID {}
Run Code Online (Sandbox Code Playgroud)

正在添加具有特定通用参数的扩展Dictionary

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

typealias BeaconID = Dictionary<Key: String, Value: NSObject>
Run Code Online (Sandbox Code Playgroud)

但这也无法编译,那是因为在 Swift 中你不能输入别名部分类型(换句话说,没有特定泛型参数类型的泛型类型。请参阅此处了解更多信息)。对泛型类型进行类型别名化的一种可能的解决方法是在我链接到的答案下面指出的

struct Wrapper<Key: Hashable, Value> {
    typealias T = Dictionary<Key, Value>
}
typealias BeaconID = Wrapper<String, NSObject>.T
Run Code Online (Sandbox Code Playgroud)

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

“必须在非特化泛型类型‘Dictionary’上声明约束扩展,并使用‘where’子句指定约束”