Aashish
Aashish

Reputation: 2706

How to get index of dictionary from an array of dictionary?

I have an array of dictionaries:

var array = [["txt":"5mbps", "value": 2048],["txt":"50mbps", "value": 18048],["txt":"55mbps", "value": 22048]]

here, I want to get the value from that index of dictionaries, which txt is being selected. If I select 50mbps, how can i get that index and display the value of the same index . - Swift

Upvotes: 1

Views: 12344

Answers (5)

Hemang
Hemang

Reputation: 27072

Latest Swift: index(where:) is deprecated you have to use firstIndex(where:) function instead.

let index = array.firstIndex(where: { ( $0["yourKey"] as? String == "compareWithValue" ) } )

Note that, this index will be optional so you can use it after proper check as per your needs.

Upvotes: 1

koropok
koropok

Reputation: 1413

use filter

func searchValue(txt: String) -> Int? {

    if let f = (array.filter { $0["txt"] == txt }).first, value = f["value"] as? Int {
        return value
    }
    return nil
}

searchValue("5mbps") // 2048
searchValue("50mbps") // 18048
searchValue("55mbps") // 22048

Upvotes: 1

Adrian Bobrowski
Adrian Bobrowski

Reputation: 2794

Maybe better use array of tuples

var array: [(txt: String, value: Int)] = [
    ("5mbps", 2048),
    ("50mbps", 18048),
    ("55mbps", 22048)
]

Swift 2.3

array.filter { element in
    return element.txt == findingText
}.first?.value

Swift 3

array.first { element in
    return element.txt == findingText
}?.value

Upvotes: 4

Ahmad F
Ahmad F

Reputation: 31665

If the case is to directly get the value from a dictionary based on given index (without using the key of the dictionary "txt"):

let givenIndexForArray = 1

if let value = array[givenIndexForArray]["value"] {
    print(value) // 18048
}

If the case is to get the value(s) based on the dictionaries' keys, you might face duplication:

In case of duplication, you need to get an array of values:

let givenKey = "50mbps"

let valueArray = array.filter { // [Optional(18048)]
    // assuming that the key is ALWAYS "txt", or value will be an empty array
    $0["txt"] == givenKey
    }
    .map {
        // assuming that the value is ALWAYS "value", or value will be an empty array
        $0["value"]
}

So, let's say that your array looks like this ("50mbps" key is duplicated):

var array = [["txt":"5mbps", "value": 2048],["txt":"50mbps", "value": 18048],["txt":"50mbps", "value": 22048]]

By applying the code snippet above, output should be: [Optional(18048), Optional(22048)].

Finally, if the case is to get just one value (or the first if there is a duplication) simply, get .first from the same valueArray array:

let first = valueArray.first // 18048

Upvotes: 0

nerezza
nerezza

Reputation: 393

to get the index you can use:

let index = array.index(where: {$0["txt"] as! String == "5mbps"})

or to get the direct value

array.filter({$0["txt"] as! String == "5mbps"}).first

Upvotes: 16

Related Questions