Ramesh
Ramesh

Reputation: 177

index(of: not appearing for [[String:Any]]

For finding index of element in array we use index(of:

let array = ["Amit","Peter", "Jhon"]
let i = array.index(of: "Peter")
print(i)//gives 1

Now i am using [[String:Any]] which is array(of dictionary)

let arrayKeyPair: [[String:Any]] = [["name":"Amit"],["name":"Peter"],["name":"Jhon"]]

Unfortunately index(of: not getting populate. Why ?

Upvotes: 1

Views: 93

Answers (5)

Hardik Bar
Hardik Bar

Reputation: 1760

let arrayKeyPair: [[String:Any]] = [["name":"Amit"],["name":"Peter"],["name":"Jhon"]]

let arrayKeyPair: [[String:Any]] = [["name":"Amit"],["name":"Peter"],["name":"Jhon"]]
let index = arrayKeyPair.index(where: {$0["name"] as? String == "Amit"})

Upvotes: 0

Parag Bafna
Parag Bafna

Reputation: 22930

You can use

    let arrayKeyPair: [[String:Any]] = [["name":"Amit"],["name":"Peter"],["name":"Jhon"]]
    let index = arrayKeyPair.index(where: {$0["name"] as? String == "Peter"})

Upvotes: 1

Shehata Gamal
Shehata Gamal

Reputation: 100503

Because of Any as what happens behind the scene of indexOf is value comparing and for sure value oftype any can't be compared

 let arrayKeyPair: [[String:Any]] = [["name":"Amit"],["name":"Peter"],["name":"Jhon"]]

change to

 let arrayKeyPair: [[String:String]] = [["name":"Amit"],["name":"Peter"],["name":"Jhon"]]

Upvotes: 1

Jigar
Jigar

Reputation: 1821

try this code

let arrayKeyPair: [[String:Any]] = [["name":"Amit"],["name":"Peter"],["name":"Jhon"]]

    let indexOfA = indexOfQuestion(id: "Peter") // 0
            print(indexOfA)

    func indexOfValue(id: String) -> Int {
            return arrayKeyPair.index { (question) -> Bool in
                return question["name"] as? String == id
                } ?? NSNotFound
        }

Upvotes: 0

PPL
PPL

Reputation: 6555

index(of: works on array where the elements conforms to the equatable protocol. you are using Any therefore it will not work.

If you really want to use index(of:), use [[String:String]], it will work.

Upvotes: 0

Related Questions