Ulrik. S
Ulrik. S

Reputation: 326

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?

Upvotes: 1

Views: 661

Answers (4)

Aaron
Aaron

Reputation: 6704

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: e.g.

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
    }
}

Upvotes: 2

gravicle
gravicle

Reputation: 324

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.

Upvotes: 1

nodyor90z
nodyor90z

Reputation: 332

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.

Upvotes: 2

Lightbeard
Lightbeard

Reputation: 4131

I think this is what you intend to do:

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

Upvotes: 1

Related Questions