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:
- Each codon code is mapped to exactly 1 English character
- Every codon code in
preEnglishInputString
is valid and can be found in yourenglishTomRNA
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
How to Use Enumeratedate in Swift 3 to Find All Sundays the Last 50 Years
Deleting with One-To-Many Relationship
Scaling Down a Text's Font Size to Fit Its Length to Another Text in Swiftui
How to Pass One Swiftui View as a Variable to Another View Struct
How to Check the Type of a Variable Against Another Variable in Swift
Nstimer Not Stopping When Invalidated in This Function
Type '()' Cannot Conform to 'View'
Shared Cookies with Wkprocesspool for Wkwebview in Swift
Macos App Local Notification Not Showing When Testing with Xcode
Swift Threading with Dispatchgroup
Cant Change Navigation Bar Height iOS 11
Using Xcode to Cross-Compile Swift to Linux
Create JSON Object from Class in Swift
What Is Existentialmetatype in Swift
How to Save Value in Nsset Core Data (Swift)