如何在 Swift 中过滤字符串数组
Posted
技术标签:
【中文标题】如何在 Swift 中过滤字符串数组【英文标题】:How to filter String array in Swift 【发布时间】:2017-08-30 13:31:53 【问题描述】:通过使用 objective 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)
请给出如何快速过滤数组的解决方案。
【问题讨论】:
【参考方案1】:使用此代码:
let yearArray: [String] = ... // your array of type [String]
let filteredArray = yearArray.filter
!$0.isEmpty
看图输出:
【讨论】:
我使用了你的代码,但是它显示错误,表达式类型不明确,没有更多上下文。 你的数组是 [String] 类型的还是不同的? 字符串类型的NSMutableArray 如果您使用 Swift,如果您的情况没有什么特别之处,您应该使用 Swift 类型。而不是“NSMutableArray”,您可以使用“var array: [String]”。 如果你仍然使用 Objective-c 类型,我认为你应该仍然可以使用 NSPredicate。但正如 Alexander 所说,在编写 swift 代码时最好使用 swift 类型!【参考方案2】:您可以使用过滤器(Array
类型)来做到这一点:
let filteredArray = yearArray.filter$0 != ""
就这么简单。
如果您的数组是 NSMutableArray
,只需将其转换为 [String]
:
if let yearArray = yearArray as? [String]
let filteredArray = yearArray.filter$0 != ""
// add your code here
【讨论】:
!$0.isEmpty
优于 $0 != ""
。它更好地传达意图。以上是关于如何在 Swift 中过滤字符串数组的主要内容,如果未能解决你的问题,请参考以下文章