2

I started this question for the purpose of asking it, but upon research I found an answer, so I compiled the answer here to share. Please let me know if it can be improved or if I have any errors.

I made an array of dictionaries where a 'tuple' (fake tuple, actually a class) is the key and a bool is the value.

I wanted something to this effect:

var dict = [(Int, Int): Bool]()
var pointDictionaryArray = [dict]()

of better compressed:

var pointDictionaryArray = [[(Int, Int): Bool]]()

However, upon research, I can't use a tuple as a key, because it's not hashable, but it seems that I can use a struct or class instead.

There is a very thorough answer given, but it was a bit confusing for me, so I'm sharing what I learned from it in a simplified manner for others.

// 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]]()

Assigning data example:

I'm using it to sort data from pixels similarly to this.

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
            }
            ...
        }
    }
    ...
}

Retrieving data example:

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")
                }
            }
        }
    }
}

Again, if I made any errors or if there are improvements to be made, let me know in the comments and I'll do my best to fix it.

Community
  • 1
  • 1
brw59
  • 502
  • 4
  • 19

0 Answers0