2016-09-30 73 views
0

我有一個字符串與前綴。我遍歷一個字符串數組,如果該值包含前綴,那麼我想從Array中刪除該項。我的代碼給我的錯誤:如何遍歷數組並刪除基於字符串值的項目

fatal error: Index out of range.

我需要一些方向如何處理這樣的事情。

for (index, value) in arrayValues.enumerated() { 
    if value.contains(prefixValue) { 
     arrayValues.remove(at: index) 
    } 
} 
+1

如何定義你的arrayValues? –

+0

var arrayValues = JSON [「array」] as? [字符串],我正在下載這個表單API –

+0

而'print(arrayValues)'輸出是? –

回答

5

您是否嘗試過使用filter

var filterArray = arrayValues.filter { !$0.contains(prefixValue) } 

對於不區分大小寫夫特3

var filterArray = arrayValues.filter { !$0.lowercased().contains(prefixValue) } 

對於不區分大小寫的SWIFT 2.3或更低

var filterArray = arrayValues.filter { !$0.lowercaseString.contains(prefixValue) } 

編輯:我有filtercontains陣列因爲OP問問題與包含但由於某種原因,其他人認爲這是錯誤的答案。所以現在我加filterhasPrefix

var filterArray = arrayValues.filter { !$0.lowercased().hasPrefix(prefixValue) } 
+0

謝謝,它的工作! –

+0

歡迎隊友:) –

+1

這將過濾在其中任何地方包含'reh'的字符串。 –

1

爲了與比較的你正在做我應該使用hasPrefixrange方法的類型更加明確:

import Foundation 

let foo = "test" 
let arrayValues = ["Testy", "tester", "Larry", "testing", "untested"] 

// hasPrefix is case-sensitive 
let filterArray = arrayValues.filter { 
    $0.hasPrefix(foo) 
} 

print(filterArray) // -> "["tester", "testing"]\n" 

/* Range can do much more, including case-insensitive. 
    The options [.anchored, .caseInsensitive] mean the search will 
    only allow a range that starts at the startIndex and 
    the comparison will be case-insensitive 
*/ 
let filterArray2 = arrayValues.filter { 
    // filters the element if foo is not found case-insensitively at the start of the element 
    $0.range(of: foo, options: [.anchored, .caseInsensitive]) != nil 
} 


print(filterArray2) // -> "["Testy", "tester", "testing"]\n" 
+0

這樣做很有道理!謝謝 –

+0

我在示例中添加了hasPrefix方法來顯示簡單的區分大小寫的比較結果。 – ColGraff

+0

這應該是正確的答案。除「$ 0」外將是「!$ 0」。 –