2016-09-30 74 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”。 –