Home > Net >  Swift - Creating and reading a 2D HashMap
Swift - Creating and reading a 2D HashMap

Time:12-03

I can't find any proper tutorial of how to do this.

I tried:

var hashMap = [Int:[String:String]]()

hashMap[7]["height"] = "bla"
hashMap[7]["align"] = "blatoo"

print(hashMap[7]["height"])

It prints nil

How to do this?

CodePudding user response:

It doesn't even compile, because the getter of the first level ([7]) may return nil. To make it work like you intend to, you need to tell the getter to return a default value in case the entry doesn't exist. You want it to return a new, empty dictionary in this case:

var hashMap = [Int:[String:String]]()

hashMap[7, default: [:]]["height"] = "bla"
hashMap[7, default: [:]]["align"] = "blatoo"

print(hashMap[7]?["height"])

To make it little nicer to use, you can provide a setter function:

func set(int: Int, key: String, value: String) {
    hashMap[int, default: [:]][key] = value
}

set(int: 7, key: "height", value: "bla")
set(int: 7, key: "align", value: "blatoo")

CodePudding user response:

In your type [Int:[String:String]] there is first is the key is type Int and the value is dict [String:String] and the dict [String:String] has key is type String and value is String

So [String:String] here is value of key 7 in your hashMap

The right way to do that is creating a dict which will be the value of key 7

Code will be like this

var hashMap = [Int:[String:String]]()

var dict = [String:String]()

dict["height"] = "bla"
dict["align"] = "blatoo"

hashMap[7] = dict

print("hashmap: ", hashMap[7]?["height"]) // Optional("bla")
  • Related