2017-08-30 90 views
0

通過使用目標C我有過濾一年陣列使用NSPredicate如何過濾字符串數組中的斯威夫特

下面是代碼。

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

按照上面的代碼它的工作目標C細,我一定要在斯威夫特3,濾波器陣列

什麼是輸入年份陣列: -

(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) 

請給解決方案如何快速過濾數組。

回答

3

使用此代碼:

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

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

看圖片輸出:

Example

+0

我用你的代碼,但是它的示值誤差,表達的類型是沒有更多的上下文曖昧。 –

+0

是你的[String]類型還是不同的數組? –

+0

字符串類型的NSMutableArray –

3

您可以通過使用過濾器(上Array型)做到這一點:

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

就這麼簡單。

如果陣列是一個NSMutableArray,只需將其轉換爲[String]

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

'!$ 0.isEmpty'比'$ 0!=「」'更可取。它更好地交流意圖。 – Alexander