我开始提出这个问题是为了询问它,但经过研究我找到了答案,所以我在这里汇总了答案。如果可以改进或者我有任何错误,请告诉我。
我制作了一个字典数组,其中'元组'(假元组,实际上是一个类)是键,而bool是值。
我想要一些这样的效果:
var dict = [(Int, Int): Bool]()
var pointDictionaryArray = [dict]()
更好的压缩:
var pointDictionaryArray = [[(Int, Int): Bool]]()
然而,经过研究,我不能使用元组作为键,因为它不可清除,而是it seems that I can use a struct or class instead。
有一个very thorough answer,但这对我来说有点混乱,所以我正在以简化的方式分享我从中学到的东西。
// have an array of dictionaries with a tuple of the x,y being the key and a boolean being the value for each pixel array
class TupleClass: Hashable {
var x: Int!
var y: Int!
init(newX: Int, newY: Int) {
x = newX
y = newY
}
// required for the Hashable protocol
var hashValue: Int {
return x * y + y
}
}
// required function for the Equatable protocol, which Hashable inherits from
func ==(left: TupleStruct, right: TupleStruct) -> Bool {
return (left.x == right.x) && (left.y == right.y)
}
var pointDictionaryArray = [[TupleClass: Bool]]()
分配数据示例:
我正在使用它来对像素中的数据进行排序。
for i in 0..<image.count {
...
for j in 0..<imageWidth {
for k in 0..<imageHeight {
...
tempTuple = TupleClass(j, k)
...
if (/*pixel is white */) {
(pointDictionaryArray[i])[tempTuple] = true
} else {
(pointDictionaryArray[i])[tempTuple] = false
}
...
}
}
...
}
检索数据示例:
for var i = 0; i < pointDictionaryArray.count; i++ {
for var j = 0; j < imageWidth; j++ {
for var k = 0; k < imageHeight; k++ {
let tempTuple = TupleClass(newX: j, newY: k)
// check to see if there is a key-value pair for the tempTuple used
if let temp = pointDictionaryArray[i][tempTuple] {
if temp {
print("true")
} else {
print("false")
}
}
}
}
}
同样,如果我犯了任何错误或者有任何改进,请在评论中告诉我,我会尽力解决。