为简化起见.让我们说我有一些独特的价值观 – 数字从1到10 现在我希望1-5映射到值“first”,我希望6-10映射到值“second” 有没有办法可以创建或扩展字典以便像下面一样工作? let dict
现在我希望1-5映射到值“first”,我希望6-10映射到值“second”
有没有办法可以创建或扩展字典以便像下面一样工作?
let dict: [Range<Int> : String]
目标是获得以下结果:
print(dict[1]) // prints first print(dict[2]) // prints first print(dict[3]) // prints first print(dict[7]) // prints second print(dict[8]) // prints second print(dict[9]) // prints second
我目前的做法是简单地将多个键映射到相同的值.但我的词典有时可以有60k的值.所以我想知道一个范围是否可行.
我知道我可以将值转换为类而不是结构,以便多个键可以映射到同一个类对象,但我想知道是否只是创建一个像上面那样工作的字典是可能的吗?
如果你坚持使用Dictionary,你必须等到Swift 3.1(目前处于测试阶段):extension CountableClosedRange : Hashable { public var hashValue: Int { return "\(lowerBound) to \(upperBound)".hashValue } } // This feature is called concrete-type extension and requires Swift 3.1 extension Dictionary where Key == CountableClosedRange<Int> { subscript(rawValue rawValue: Int) -> Value? { for k in self.keys { if k ~= rawValue { return self[k] } } return nil } } let dict : [CountableClosedRange<Int>: String] = [ 1...5: "first", 6...10: "second" ] print(dict[rawValue: 1]) print(dict[rawValue: 2]) print(dict[rawValue: 3]) print(dict[rawValue: 7]) print(dict[rawValue: 8]) print(dict[rawValue: 9])
但是,如果您实现自己的数据模型,它会更清晰:
struct MyRange { var ranges = [CountableClosedRange<Int>]() var descriptions = [String]() mutating func append(range: CountableClosedRange<Int>, description: String) { // You can check for overlapping range here if you want self.ranges.append(range) self.descriptions.append(description) } subscript(value: Int) -> String? { for (i, range) in self.ranges.enumerated() { if range ~= value { return descriptions[i] } } return nil } } var range = MyRange() range.append(range: 1...5, description: "one") range.append(range: 6...10, description: "second") print(range[1]) print(range[2]) print(range[6]) print(range[7]) print(range[100])