Home > Blockchain >  Clarification on Swift line of dictionary and possible translation of map[x]!.append(product) to Kot
Clarification on Swift line of dictionary and possible translation of map[x]!.append(product) to Kot

Time:09-16

I have a line in Swift that is:

var map: [String:[String]] = [String:[String]]()
map[x]!.append(product)

I am curious what the implementation map[x]!.append(product) is meant to be, additionally what an appropriate translation to Kotlin would be.

CodePudding user response:

Lets start by breaking this line down in to smaller parts:

map[x]!.append(product)

By default, hash maps return an optional because it may or may not contain the given key. So think of this as the type:

map[x] // Gives us a [String]?

There are a few ways you can unwrap the optional. The least safe, but easiest way to obtain this is by using explicit unwrapping (using an !)

 map[x]! // Gives us a [String]

To add to an existing array, use the append() method. Calling:

map[x]!.append(product)

Adds the product to the array of strings.

Example of appending to an array:

var fruitArray = ["Apple", "Banana"]
var newFruit = "Orange"
fruitArray.append(newFruit)
// fruitArray will now be ["Apple", "Banana", "Orange"]

Example of a map containing an array that you want to add to:

var productMap = ["fruits": ["Apple", "Banana"]] 
// productMap["fruits"] is ["Apple", "Banana"]

// This is a new fruit we want to add
var newFruit = "Orange"

// Lets add new fruit to fruits
productMap["fruits"].append(newFruit)
// productMap["fruits"] will now be ["Apple", "Banana", "Orange"]

Kotlin equivalent of the given code:

val map:HashMap<String,MutableList<String>> = HashMap<String,MutableList<String>>();
map[x]!!.add(product);

CodePudding user response:

Sam's answer is good, but I recommend slightly different Kotlin syntax:

val map = mutableMapOf<String, MutableList<String>>()
map.getValue("x").add("product")

In general, I recommend not explicitly defining types and instead letting them be inferred. I also prefer using the stdlib mutableMapOf() function to an explicit call to the HashMap constructor.

Finally, I suggest using getValue() instead of []!! when accessing the map for a key that you know is present. If you don't know 100% for sure, then I suggest using null-safe access:

map["x"]?.add("product")
  • Related