如何在数组中查找字符串元素,无论大小写

时间:2015-08-28 07:19:14

标签: ios arrays swift case-sensitive

如果myString中存在myArray,我想显示提醒:

var myString = "A"
var myArray = [A]
if contains(self.arrayGroup, self.txtGroupName.text) {
   let alert = UIAlertView()
        alert.title = "Sorry :("
        alert.message = "Duplicate Name"
        alert.addButtonWithTitle("OK")
        alert.show()
}

但如果myString的情况相反,则警报未显示:(

var myStr = "As"
var myArr = [AS]
if contains(self.arrayGroup, self.txtGroupName.text) {
   let alert = UIAlertView()
        alert.title = "Sorry :("
        alert.message = "Duplicate Name"
        alert.addButtonWithTitle("OK")
        alert.show()
}

如何在myString忽略案例中找到myArray

1 个答案:

答案 0 :(得分:1)

我猜你正在寻找的东西如下:

let search = "b"
let arrayToSearch = ["A", "B", "C"]
let searchResult = arrayToSearch.filter() { $0.caseInsensitiveCompare(search) == NSComparisonResult.OrderedSame }
if searchResult.count != 0 {
    print("'\(search)' matched to '\(searchResult[0])'")
} else {
    print("'\(search)'not found")
}

将输出

  

' B'匹配' B'