简体   繁体   English

如何在Swift中过滤String数组

[英]How to filter String array in Swift

By using objective C I have filter year array by using NSPredicate , 通过使用目标C我使用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 , 按照上面的代码,它在目标c中工作正常,我必须在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. 请给出解决方案如何在swift中过滤数组。

Use this code: 使用此代码:

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

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

Look at the picture for output: 看图片输出:

例

You can do it by using filter (on an Array type) : 您可以使用filter(在Array类型上)来执行此操作:

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

It's that simple. 就这么简单。

If your array is an NSMutableArray , just cast it to [String] : 如果您的数组是NSMutableArray ,只需将其NSMutableArray[String]

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM