如何在Swift中过滤String数组

时间:2017-08-30 13:31:53

标签: ios arrays swift swift3

使用目标C 我使用 NSPredicate 来获取过滤年份数组,

下面是代码。

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

按照上面的代码,它在目标c中运行良好,我必须在 Swift 3 中过滤数组,

什么是输入年数组: -

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

需要过滤器输出数组

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

请给出解决方案如何在swift中过滤数组。

2 个答案:

答案 0 :(得分:4)

使用此代码:

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

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

查看图片输出:

Example

答案 1 :(得分:4)

您可以使用过滤器(在Array类型上):

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

就这么简单。

如果您的数组是NSMutableArray,只需将其转换为[String]

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