How to Add Multiple Values for One Key in a Dictionary Using Swift

Multiple values for one Key in Swift Dictionary

You're getting a bad error message. The real issue is that [Bool, String] isn't a valid type. There is no way to specify an array of fixed length with specific types in specific spots. Instead, use a tuple:

var cat1 = [String: (Bool, String)]()
var cat2: [String: (Bool, String)] = ["Bob": (false, "Red"), "Albert": (true, "Black")]

Dictionary with Multiple Keys for a Single Value - Swift

Use Swift's higher order functions:

var englishTomRNA: [Character: [String]] = ["A": ["UUU", "UAC"],
"Q": ["UUA"],
"S": ["UCU", "UCC", "UCA"]]
var inEnglish = ""

// Sample Input
let preEnglishInputString = ["UUA", "UCC", "UUU"]

for codon in preEnglishInputString {
let english = englishTomRNA
.filter { $0.1.contains(codon) }
.first!.0
inEnglish.append(english)
}

print(inEnglish) // QSA

This works with 2 assumptions:

  1. Each codon code is mapped to exactly 1 English character
  2. Every codon code in preEnglishInputString is valid and can be found in your englishTomRNA dictionary.

What it does:

.filter { ... } finds any key-value pair that contains the codon. When you call filter on a Dictionary, it degenereates into a tuple of (key, value) so $0.1 refers to the value. filter always return an array of matches, even if it finds only one match.

first! gets the first match from the list (assumption 1). The exclamation mark assumes that a match is always found (assumption 2).

.0 gets the key of the key-value pair, which the English character.

how to add multiple key value pairs to dictionary Swift

This is how dictionary works:

In computer science, an associative array, map, symbol table, or
dictionary is an abstract data type composed of a collection of (key,
value) pairs, such that each possible key appears at most once in the
collection.

So

var cart = [String:String]() 
cart["key"] = "one"
cart["key"] = "two"
print(cart)

will print only "key" - "two" part. It seems that you may need an array of tuples instead:

var cart = [(String, String)]() 
cart.append(("key", "one"))
cart.append(("key", "two"))
print(cart)

will print both pairs.



Related Topics



Leave a reply



Submit