Swift 4.2 字典无法通过键找到值

标签 swift

我生成键来通过某些函数选择字典的值。 当我比较生成的键和字典中的键的哈希值时,它们是相同的。但是,如果我尝试通过生成的键从字典中获取某些内容 - 我得到的是零。

let vCoords = verticesFrom(axes: result)
print ("Generated:")
vCoords.forEach { 
    print($0, $0.hashValue)
}
print ("Stored:")
grid.forEach {
    print($0.key, $0.key.hashValue, $0.value.data)
}

let data1 = vCoords.map { grid[$0]?.data }.compactMap{$0}

print ("\nData: \(data1)")

列表为:

Generated:
["x": -100.0, "y": -100.0] 8549935799981594856
["x": -100.0, "y": -50.0] -5857979117386601619
["x": -10.0, "y": -100.0] 5216433118710295311
["x": -10.0, "y": -50.0] 3277190687522282455
Stored:
["x": -100.0, "y": -100.0] 8549935799981594856 [NSCalibratedRGBColorSpace 1 1 1 1]
["x": -100.0, "y": -50.0] -5857979117386601619 [NSCalibratedRGBColorSpace 0.583333 0.583333 0.583333 0.666667]
["x": -10.0, "y": -100.0] 5216433118710295311 [NSCalibratedRGBColorSpace 0.685 0.685 0.685 1]
["x": -10.0, "y": -50.0] 3277190687522282455 [NSCalibratedRGBColorSpace 0 0 1 1]

Data: []

当然,我可以通过网格迭代 vCoords 并比较每个值,但在这种情况下我不需要字典,并且算法速度较慢。可能出了什么问题?

最佳答案

您似乎在这里返回了一个字典数组:

let vCoords = verticesFrom(axes: result)

具体来说类似于(但不是字典,因为它已经符合 Equatable)

[[String: Int]]    
[["x": -100.0, "y": -100.0], ["x": -100.0, "y": -50.0].... ]

为了获得预期的结果,您需要更改以下内容:

如果您还没有为您的项目创建自定义对象

verticesFrom(轴:结果)

您应该创建一个自定义类并使其符合 Equatable 协议(protocol):

class CustomCoordinate: Equatable {    
    var customX: Int
    var customY: Int

// ...
   public static func == (lhs: CustomCoordinate, rhs: CustomCoordinate) -> Bool {
        return lhs.customX == rhs.customX && lhs.customY == rhs.customY
    }
}

否则,如果这意味着您的项目中有太多更改并且您需要快速修复:

let data1 = vCoords.map ({ vectCoord -> [String: Int]? in // [String: Int]? or whatever objet you are using
    grid.first(where: { (customCoord) -> Bool in
        return customCoord["x"] == vectCoord["x"] && customCoord["y"] == vectCoord["y"]
    })
}).compactMap{$0}

关于Swift 4.2 字典无法通过键找到值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52703078/

相关文章:

ios - 从 web url 在 UIAlertAction 中添加图像

swift - 虽然是可选的,但如果包含某些内容则展开

swift - 为什么不调用 UICollectionView insetForSectionsAtIndex?

swift - 如何在快速搜索字典时使用可选链接?

swift - 在 RealmSwift 中存储 float 数组

ios - xml SOAP 与 swift (IOS 8)

objective-c - swift 3 : stringByReplacingCharactersInRange alternatives

iOS RxSwift 如何将核心蓝牙连接到 Rx 序列?

swift - 将第三方C库导入到swift中会导致错误 "Include of non-modular header inside framework module"

ios - 符合协议(protocol)的元素集合 ? : Viewer Swift