在Swift中,如何扩展typealias? [英] In Swift, how to extend a typealias?
问题描述
我有一个别名:
typealias BeaconId = [String: NSObject]
我想通过做类似的事情来扩展它:
I'd like to extend it by doing something like:
extension BeaconId {}
但这会引发编译错误:
必须在具有"where"子句指定约束的非专业通用类型字典"上声明受约束的扩展名
Constrained extension must be declared on the unspecialized generic type 'Dictionary' with constraints specified by a 'where' clause
所以我最终做了:
extension Dictionary where Key: StringLiteralConvertible, Value: NSObject {}
是否有一种更清洁的方式来做到这一点?
Is there a cleaner way to do this?
推荐答案
AFAIK,否.
请考虑以下示例:
typealias Height: Float
extension: Height {
}
这里Height
不是新类型,它只是Float
的标签,因此您只是扩展Float
.如果您查看Dictionary
,它是public struct Dictionary<Key : Hashable, Value> : CollectionType, DictionaryLiteralConvertible
,那么您要尝试实现的目标
Here Height
is not a new type, it's just a label for Float
so you're just extending Float
. If you take a look at Dictionary
it's public struct Dictionary<Key : Hashable, Value> : CollectionType, DictionaryLiteralConvertible
so what you'd be trying to achieve with
extension BeaconID {}
正在使用特定的通用参数为Dictionary
添加扩展名.
is adding an extension to Dictionary
with specific generic parameters.
我希望您应该能够做的是:
What I would expect that you should be able to do is:
typealias BeaconID = Dictionary<Key: String, Value: NSObject>
但这也无法编译,这是因为在Swift中您不能键入部分类型的别名(换句话说,没有特定泛型参数类型的泛型.请参见
but that also doesn't compile and that's because in Swift you can't typealias partial types (in other words generic types without specific generic parameter types. See here for more info). A possible workaround for typealiasing generic types which is noted below the answer I linked to is
struct Wrapper<Key: Hashable, Value> {
typealias T = Dictionary<Key, Value>
}
typealias BeaconID = Wrapper<String, NSObject>.T
但是即使在尝试扩展BeaconID
时,也会收到编译器警告,该警告最终成为问题的核心:
but even then when you try to extend BeaconID
, you get a compiler warning, which finally gets to the heart of the problem:
必须在具有'where'子句指定约束的非专业通用类型'Dictionary'上声明受约束的扩展"
"Constrained extension must be declared on the unspecialized generic type 'Dictionary' with constraints specified by a 'where' clause"
这篇关于在Swift中,如何扩展typealias?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!