Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested Swift Dictionaries

Tags:

swift

I want to initialize a dictionary with a dictionary nested inside like this:

var a = [Int:[Int:Float]]()
a[1][2] = 12

But I get an error:

(Int:[Int:Float]) does not have a member named 'subscript'

I've hacked at a variety of other approaches, all of them running into some kind of issue.

Any idea why this doesn't work?

like image 223
Chet Avatar asked Feb 13 '23 08:02

Chet


1 Answers

You can create your own 2D dictionary like this:

struct Dict2D<X:Hashable,Y:Hashable,V> {
    var values = [X:[Y:V]]()
    subscript (x:X, y:Y)->V? {
        get { return values[x]?[y] }
        set {
            if values[x] == nil {
                values[x] = [Y:V]()
            }
            values[x]![y] = newValue
        }
    }
}
var a = Dict2D<Int,Int,Float>()
a[1,2] = 12
println(a[1,2]) // Optional(12.0)
println(a[0,2]) // nil

The point is you access the element via a[x,y] instead of a[x][y] or a[x]?[y].

like image 150
dankogai Avatar answered Feb 14 '23 20:02

dankogai