Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to filter array in Swift

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 342
    Comment on it

    Hi Readers,

    In iOS app many times we have to filter our results according to requirement. We can filter array of results same as following example. Let say we have an array(articleArray) like:

    (
            {
            Read = 0;
            Saved = 0;
            Shared = 0;
    author = 10;
    "comment_status" = open;
    date = "2016-07-06T13:10:13";
    "primary_type" = article;
    }
    
            {
            Read = 0;
            Saved = 0;
            Shared = 0;
    author = 10;
    "comment_status" = open;
    date = "2016-07-06T13:10:13";
    "primary_type" = audio;
    }
    
            {
            Read = 0;
            Saved = 0;
            Shared = 0;
    author = 10;
    "comment_status" = open;
    date = "2016-07-06T13:10:13";
    "primary_type" = audio;
    }
    
            {
            Read = 0;
            Saved = 0;
            Shared = 0;
    author = 10;
    "comment_status" = open;
    date = "2016-07-06T13:10:13";
    "primary_type" = article;
    }
    
            {
            Read = 0;
            Saved = 0;
            Shared = 0;
    author = 10;
    "comment_status" = open;
    date = "2016-07-06T13:10:13";
    "primary_type" = video;
    }
    
            {
            Read = 0;
            Saved = 0;
            Shared = 0;
    author = 10;
    "comment_status" = open;
    date = "2016-07-06T13:10:13";
    "primary_type" = video;
    }
    )

    And we have to filler objects according to article_type. Let say we have to check for video and audio only. We need to first make an array with these two string like:

    let filterArray = ["audio", "video"]

    We need to make predicate for filter like:

    let namePredicate = NSPredicate(format:"primary_type IN %@",filterArray)

    We will then applied this predicate on our array like:

    let filteredArray = newfeaturedArticlesArray.filter {namePredicate.evaluateWithObject($0) };

    With this code snippet will filter all audio and video article into filteredArray and you can use if for filtering results accordingly.

    Thanks for reading :)

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: