我试图通过搜索列表找到一个项目索引。有人知道怎么做吗?

我看到有一张单子。StartIndex和list。EndIndex,但我想要类似python的list.index("text")。


当前回答

斯威夫特4

参考类型:

extension Array where Array.Element: AnyObject {

    func index(ofElement element: Element) -> Int? {
        for (currentIndex, currentElement) in self.enumerated() {
            if currentElement === element {
                return currentIndex
            }
        }
        return nil
    }
}

其他回答

斯威夫特4

参考类型:

extension Array where Array.Element: AnyObject {

    func index(ofElement element: Element) -> Int? {
        for (currentIndex, currentElement) in self.enumerated() {
            if currentElement === element {
                return currentIndex
            }
        }
        return nil
    }
}

你可以用闭包来过滤数组:

var myList = [1, 2, 3, 4]
var filtered = myList.filter { $0 == 3 }  // <= returns [3]

你可以对数组进行计数:

filtered.count // <= returns 1

所以你可以通过组合这些来确定数组是否包含你的元素:

myList.filter { $0 == 3 }.count > 0  // <= returns true if the array includes 3

如果你想找这个职位,我不认为有什么花哨的方法,但你可以这样做:

var found: Int?  // <= will hold the index if it was found, or else will be nil
for i in (0..x.count) {
    if x[i] == 3 {
        found = i
    }
}

EDIT

当我们这样做的时候,为了一个有趣的练习,让我们扩展Array来有一个find方法:

extension Array {
    func find(includedElement: T -> Bool) -> Int? {
        for (idx, element) in enumerate(self) {
            if includedElement(element) {
                return idx
            }
        }
        return nil
    }
}

现在我们可以这样做:

myList.find { $0 == 3 }
// returns the index position of 3 or nil if not found

斯威夫特5

func firstIndex(of element: Element) -> Int?

var alphabets = ["A", "B", "E", "D"]

例二

let index = alphabets.firstIndex(where: {$0 == "A"})

Example2

if let i = alphabets.firstIndex(of: "E") {
    alphabets[i] = "C" // i is the index
}
print(alphabets)
// Prints "["A", "B", "C", "D"]"

斯威夫特2.1

var array = ["0","1","2","3"]

if let index = array.indexOf("1") {
   array.removeAtIndex(index)
}

print(array) // ["0","2","3"]

斯威夫特3

var array = ["0","1","2","3"]

if let index = array.index(of: "1") {
    array.remove(at: index)
}
array.remove(at: 1)

Swift 2更新:

sequence.contains(element):如果给定序列(如 数组)包含指定的元素。

斯威夫特1:

如果你只是检查一个元素是否包含在一个数组中,也就是说,只是获取一个布尔指示符,使用contains(sequence, element)而不是find(array, element):

contains(sequence, element):如果给定序列(如 数组)包含指定的元素。

请看下面的例子:

var languages = ["Swift", "Objective-C"]
contains(languages, "Swift") == true
contains(languages, "Java") == false
contains([29, 85, 42, 96, 75], 42) == true
if (contains(languages, "Swift")) {
  // Use contains in these cases, instead of find.   
}