Kush Thakkar Kush Thakkar - 1 month ago 13
Swift Question

Get index of object from array of dictionary with key value

I have one array with dictionary.

Now i want to get index number of object with particular key value.

Like key = "xyz" and value = "abc".

I need index of object having above matching in dictionary.

{
Id = 20085;
IsNew = 1;
Title = Circular;
},
{
Id = 20088;
IsNew = 0;
Title = Query;
},
{
Id = 20099;
IsNew = 1;
Title = Blog;
},
{
Id = 20104;
IsNew = 1;
Title = News;
},
{
Id = 20172;
IsNew = 1;
Title = AssignTask;
},
{
Id = 20183;
IsNew = 1;
Title = Gallery;
},
{
Id = 20204;
IsNew = 1;
Title = Poll;
},
{
Id = 20093;
IsNew = 1;
Title = Assignment;
},
{
Id = 20209;
IsNew = 1;
Title = Activity;
},
{
Id = 20130;
IsNew = 1;
Title = Behaviour;
},
{
Id = 20180;
IsNew = 1;
Title = Result;
}


now i need index of object with having key = "Title" and value = "result"

Answer

Here is what you should be doing after using a json parser

 let array:NSArray = [
[
    "Id": 20130,
    "IsNew": 1,
    "Title":"Behaviour"
],
[
    "Id": 20180,
    "IsNew": 1,
    "Title":"Result"
]]


let k = array as Array
let index = k.indexOf {
    if let dic = $0 as? Dictionary<String,AnyObject> {
        if let value = dic["Title"]  as? String
            where value == "Result"{
         return true
        }
    }
    return false
}

print(index) // index