简体   繁体   中英

How to check a value is inside nested dictionary swift

I have a problem concerning my nested dictionary.

var level1Dictionary = [String : [String : String]]()
var ChosenDeckLabel = [String]
textview.text

I want to see if the dictionary contains a certain value within my, else if statement as such:

else if level1Dictionary[ChosenDeckLabel[textview.text]] != nil {

this returns error:

Cannot subscript value of type String with an index of type String!

How should I cast it to check if the nested dictionary contains the value?

Dictionaries are optionals by default because they are not sure if a key/value pair exist. Be sure to include your "!" AND "?" to wrap and unwrap your data being passed.

Arrays offer subscripting via integers and ranges as seen in Swift's API:

public subscript (index: Int) -> Element
public subscript (subRange: Range<Int>) -> ArraySlice<Element>

You're trying to subscript via a string which is throwing the error. You need to get the index of the element in the array and then use that to subscript the array to get the value: eg

let dictOfDicts = [String : [String : String]]()
var arrayOfStrings: [String] = ["a", "b", "c"]
let stringToCheck = "a"

dictOfDicts["a"] = ["some": "thing"]

if let index = array.indexOf(stringToCheck) {
    if dictOfDicts[array[Int(index)]] != nil {
        // do something
    }
}

我认为这是您打算做的:

else if level1Dictionary[strIndex1][strIndex2] != nil {

When you are doing this:

level1Dictionary[ChosenDeckLabel[textview.text]]

you are trying to access the ChosenDeckLabel array using a String subscript:

ChosenDeckLabel[textview.text]

which is not a valid operation. Arrays are Int indexed and not string indexed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM