首页 文章

如何在Swift中找到列表项的索引?

提问于
浏览
351

我试图通过搜索列表找到项目索引 . 有谁知道怎么做?

我看到有 list.StartIndexlist.EndIndex 但我想要类似python的 list.index("text") .

16 回答

  • 5

    虽然 indexOf() 完美无缺, it only returns one index.

    我正在寻找一种优雅的方法来获取满足某些条件的元素的索引数组 .

    以下是它的完成方式:

    Swift 3:

    let array = ["apple", "dog", "log"]
    
    let indexes = array.enumerated().filter {
        $0.element.contains("og")
        }.map{$0.offset}
    
    print(indexes)
    

    Swift 2:

    let array = ["apple", "dog", "log"]
    
    let indexes = array.enumerate().filter {
        $0.element.containsString("og")
        }.map{$0.index}
    
    print(indexes)
    
  • 148

    任何此解决方案都适合我

    这是我对Swift 4的解决方案:

    let monday = Day(name: "M")
    let tuesday = Day(name: "T")
    let friday = Day(name: "F")
    
    let days = [monday, tuesday, friday]
    
    let index = days.index(where: { 
                //important to test with === to be sure it's the same object reference
                $0 === tuesday
            })
    
  • 2

    如果你还在使用Swift 1.x

    然后尝试,

    let testArray = ["A","B","C"]
    
    let indexOfA = find(testArray, "A") 
    let indexOfB = find(testArray, "B")
    let indexOfC = find(testArray, "C")
    
  • 2

    Swift 4.如果您的数组包含[String:AnyObject]类型的元素 . 所以要找到元素的索引使用下面的代码

    var array = [[String: AnyObject]]()// Save your data in array
    let objectAtZero = array[0] // get first object
    let index = (self.array as NSArray).index(of: objectAtZero)
    

    或者如果你想在Dictionary的基础上找到索引 . 这里数组包含Model类的对象,我匹配id属性 .

    let userId = 20
    if let index = array.index(where: { (dict) -> Bool in
           return dict.id == userId // Will found index of matched id
    }) {
    print("Index found")
    }
    
  • 77

    Swift 2.1

    var array = ["0","1","2","3"]
    
    if let index = array.indexOf("1") {
       array.removeAtIndex(index)
    }
    
    print(array) // ["0","2","3"]
    

    Swift 3

    var array = ["0","1","2","3"]
    
    if let index = array.index(of: "1") {
        array.remove(at: index)
    }
    array.remove(at: 1)
    
  • 0

    您还可以使用函数库Dollar在数组上执行indexOf http://www.dollarswift.org/#indexof-indexof

    $.indexOf([1, 2, 3, 1, 2, 3], value: 2) 
    => 1
    
  • 13

    Swift 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
        }
    }
    
  • 12

    在Swift 2(使用Xcode 7)中, Array 包含CollectionType协议提供的indexOf方法 . (实际上,两个 indexOf 方法 - 一个使用相等来匹配一个参数,一个another使用一个闭包 . )

    在Swift 2之前,像集合这样的泛型类型没有办法为从它们派生的具体类型(如数组)提供方法 . 因此,在Swift 1.x中,"index of"是一个全局函数......它也被重命名,所以在Swift 1.x中,该全局函数被称为 find .

    也可以(但不是必须)使用 NSArray 中的 indexOfObject 方法...或者任何其他更复杂的基础搜索方法,它在Swift标准库中没有等价物 . 只需 import Foundation (或另一个传递Foundation的模块),将 Array 强制转换为 NSArray ,并且可以在 NSArray 上使用多种搜索方法 .

  • 2

    Swift 4 中,如果遍历DataModel数组,请确保您的数据模型符合Equatable Protocol,实现lhs = rhs方法,然后才能使用".index(of" . 例如

    class Photo : Equatable{
        var imageURL: URL?
        init(imageURL: URL){
            self.imageURL = imageURL
        }
    
        static func == (lhs: Photo, rhs: Photo) -> Bool{
            return lhs.imageURL == rhs.imageURL
        }
    }
    

    然后,

    let index = self.photos.index(of: aPhoto)
    
  • 4

    对于SWIFT 3,您可以使用简单的功能

    func find(objecToFind: String?) -> Int? {
       for i in 0...arrayName.count {
          if arrayName[i] == objectToFind {
             return i
          }
       }
    return nil
    }
    

    这将给出数字位置,所以你可以使用喜欢

    arrayName.remove(at: (find(objecToFind))!)
    

    希望有用

  • 9

    你可以 filter 一个带闭包的数组:

    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

    虽然我们're at it, for a fun exercise let'扩展 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
    
  • 0

    对于自定义类,您需要实现Equatable协议 .

    import Foundation
    
    func ==(l: MyClass, r: MyClass) -> Bool {
      return l.id == r.id
    }
    
    class MyClass: Equtable {
        init(id: String) {
            self.msgID = id
        }
    
        let msgID: String
    }
    
    let item = MyClass(3)
    let itemList = [MyClass(1), MyClass(2), item]
    let idx = itemList.indexOf(item)
    
    printl(idx)
    
  • 21

    Swift 4.2

    func index(of element: Element) -> Int?
    
    var alphabets = ["A", "B", "E", "D"]
    

    例1

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

    例题

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

    Update for Swift 2:

    sequence.contains(element):如果给定序列(如数组)包含指定元素,则返回true .

    Swift 1:

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

    contains(sequence,element):如果给定序列(如数组)包含指定元素,则返回true .

    见下面的例子:

    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.   
    }
    
  • 671

    由于swift在某些方面比面向对象更具功能性(并且Arrays是结构,而不是对象),因此使用函数“find”对数组进行操作,该函数返回一个可选值,因此请准备好处理nil值:

    let arr:Array = ["a","b","c"]
    find(arr, "c")!              // 2
    find(arr, "d")               // nil
    

    Update for Swift 2.0:

    使用Swift 2.0不再支持旧的 find 功能了!

    使用Swift 2.0, Array 获得了使用 CollectionTypeArray implements)扩展中定义的函数查找元素索引的能力:

    let arr = ["a","b","c"]
    
    let indexOfA = arr.indexOf("a") // 0
    let indexOfB = arr.indexOf("b") // 1
    let indexOfD = arr.indexOf("d") // nil
    

    此外,查找满足谓词的数组中的第一个元素是由 CollectionType 的另一个扩展支持的:

    let arr2 = [1,2,3,4,5,6,7,8,9,10]
    let indexOfFirstGreaterThanFive = arr2.indexOf({$0 > 5}) // 5
    let indexOfFirstGreaterThanOneHundred = arr2.indexOf({$0 > 100}) // nil
    

    请注意,这两个函数返回可选值,如之前 find 所做的那样 .

    Update for Swift 3.0:

    请注意indexOf的语法已更改 . 对于符合 Equatable 的物品,您可以使用:

    let indexOfA = arr.index(of: "a")
    

    有关该方法的详细文档,请访问https://developer.apple.com/reference/swift/array/1689674-index

    对于不符合 Equatable 的数组项,您需要使用 index(where:)

    let index = cells.index(where: { (item) -> Bool in
      item.foo == 42 // test if this is the item you're looking for
    })
    

    Update for Swift 4.2:

    使用Swift 4.2时,不再使用 index ,但为了更好地说明,将其分为 firstIndexlastIndex . 因此,取决于您是否正在寻找项目的第一个或最后一个索引:

    let arr = ["a","b","c","a"]
    
    let indexOfA = arr.firstIndex(of: "a") // 0
    let indexOfB = arr.lastIndex(of: "a") // 3
    
  • 2

    我认为值得一提的是,使用引用类型( class ),您可能希望执行身份比较,在这种情况下,您只需要在谓词闭包中使用 === identity运算符:

    Swift 4 / Swift 3:

    let person1 = Person(name: "John")
    let person2 = Person(name: "Sue")
    let person3 = Person(name: "Maria")
    let person4 = Person(name: "Loner")
    
    let people = [person1, person2, person3]
    
    let indexOfPerson1 = people.index{$0 === person1} // 0
    let indexOfPerson2 = people.index{$0 === person2} // 1
    let indexOfPerson3 = people.index{$0 === person3} // 2
    let indexOfPerson4 = people.index{$0 === person4} // nil
    

    请注意,上面的语法使用尾随闭包语法,相当于:

    let indexOfPerson1 = people.index(where: {$0 === person1})
    

    Swift 2 - index 函数语法曾经是:

    let indexOfPerson1 = people.indexOf{$0 === person1}
    

    *注意实现 Equatable 的相关且有用的comment关于 class 类型,您需要考虑是否应使用 === (身份运算符)或 == (相等运算符)进行比较 . 如果您决定使用 == 进行匹配,则可以使用其他人建议的方法( people.index(of: person1) ) .

相关问题