我有一个类型别名:
typealias BeaconId = [String: NSObject]
我想通过做类似的事情来扩展它:
extension BeaconId {}
但这会引发编译错误:
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 {}
有没有更简洁的方法来做到这一点?
最佳答案
在 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 squared = 4
关于swift - 在 Swift 中,如何扩展类型别名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33771368/