2

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.

2 Answers 2

5

Use this code:

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

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

Look at the picture for output:

Example

Sign up to request clarification or add additional context in comments.

8 Comments

I have use your code , However it's showing error , Type of expression is ambiguous without more context.
is your array of type [String] or different?
NSMutableArray of type string
If you use Swift, you should use Swift types if there is nothing special about your case. And instead of "NSMutableArray" you can use "var array: [String]".
If you still use Objective-c type you should still be able to use NSPredicate I think. But as Alexander said, it's better to use swift types when you're writing swift code !
|
4

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
}

1 Comment

!$0.isEmpty is preferable to $0 != "". It better communicate intent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.