如何迭代Array并根据字符串值删除项目

时间:2016-09-30 05:52:25

标签: ios arrays swift swift3

我的字符串是前缀。我正在遍历一个String of String,如果该值包含前缀,那么我想从Array中删除该项。我的代码给了我错误:

  

致命错误:索引超出范围。

我需要一些指导如何处理这样的事情。

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

2 个答案:

答案 0 :(得分:5)

您是否尝试使用filter

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

对于不区分大小写的Swift 3

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

对于不区分大小写的Swift 2.3或更低版本

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

编辑filter数组contains因为OP已向问题提出问题,但由于某些原因,其他人认为这是错误的答案。现在我正在添加filter hasPrefix

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

答案 1 :(得分: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"