Jaywant Khedkar
Jaywant Khedkar

Reputation: 6111

How to filter String array in Swift

By using objective C I have filter year array by using NSPredicate,

Below is code.

  yearArray = [yearArray filteredArrayUsingPredicate:[NSPredicate
  predicateWithFormat:@"SELF != ''"]];

As per above code it's working fine in objective c , I have to filter array in Swift 3,

What is Input Year Array :-

( Year,"","","",JAN,"","","",FEB,"","","",MAR,"","","",APR,"","","",
  MAY,"","","",JUN,"","","",JUL,"","","",AUG,"","","",SEP,"","","",OCT
  ,"","","", NOV,"","","",DEC,"","","","",WIN,"","","",SPR,"","","",SUM
  ,"","","",AUT,"","","","",ANN)

Need filter Output Array

(Year,JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC,WIN,SPR,SUM,AUT,ANN)

Please give solution how to filter array in swift.

Upvotes: 2

Views: 4369

Answers (2)

Aleksandr Honcharov
Aleksandr Honcharov

Reputation: 2513

Use this code:

let yearArray: [String] = ... // your array of type [String]

let filteredArray = yearArray.filter {
    !$0.isEmpty
}

Look at the picture for output:

Example

Upvotes: 5

Damien
Damien

Reputation: 3362

You can do it by using filter (on an Array type) :

let filteredArray = yearArray.filter{$0 != ""}

It's that simple.

If your array is an NSMutableArray, just cast it to [String] :

if let yearArray = yearArray as? [String] {
    let filteredArray = yearArray.filter{$0 != ""}
    // add your code here
}

Upvotes: 4

Related Questions