2014-06-08 10 views

Odpowiedz

58

EDIT: Od Swift 3.0, należy użyć metody .index(where:) zamiast śledzić i zmiany w edycji Swift 2.0 poniżej.

EDYCJA: Od Swift 2.0 powinieneś użyć metody indexOf. Również zwraca nil lub pierwszy indeks jego argumentu.

if let i = array.indexOf("Jason") { 
    print("Jason is at index \(i)") 
} else { 
    print("Jason isn't in the array") 
} 

Użyj funkcji find. Zwraca wartość nil (jeśli wartość nie zostanie znaleziona) lub pierwszy indeks wartości w tablicy.

if let i = find(array, "Jason") { 
    println("Jason is at index \(i)") 
} else { 
    println("Jason isn't in the array") 
} 
+0

uwaga: znaleźć współpracuje z dowolnym typem obiektu w tablicy tego samego typu obiektów ... – BananaAcid

+0

'find' już nie działa dla tablic w Swift 2.0 – kakubei

+0

@kakubei dzięki aktualizowany – nathan

1

Array może być zmostkowane do NSArray, więc można użyć:

array.bridgeToObjectiveC().indexOfObject("Jason") 
+6

'bridgeToObjectiveC()' jest metodą prywatną. Zamiast tego użyj operatora 'as'. – raheel

+1

tj. (Tablica jako NSArray) .indexOfObject ("Jason") – josef

1

Przedłużenie Array może zdziałać cuda tutaj. Oto realizacja dzielone w this StackOverflow answer:

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

Swift 2.0 ma array.indexOf (...), więc nie jest to już potrzebne – n13

0

Możesz dodać Array rozszerzenie, które jest dokładnie to, co chcesz, a mianowicie:

extension Array { 
    func indexOf<T : Equatable>(x:T) -> Int? { 
     for i in 0..self.count { 
      if self[i] as T == x { 
       return i 
      } 
     } 
     return nil 
    } 
} 

które teraz pozwala używać .indexOf() wszystkich Swift tablic, np:

["Jason", "Charles", "David"].indexOf("Jason") //0 
8

że wykonane z tej funkcji, jak wyżej, ale powrót tablicę wskaźników

extension Array { 
    func indexesOf<T : Equatable>(object:T) -> [Int] { 
     var result: [Int] = [] 
     for (index,obj) in enumerate(self) { 
      if obj as T == object { 
       result.append(index) 
      } 
     } 
     return result 
    } 
} 

Może to być przydatne dla Ciebie

0

Chociaż odpowiedź od Max jest wielki, nie pozwalają znaleźć wiele indeksów z wielu obiektów, tj. indeksy podzbioru tablicy. Jeśli potrzebujesz tej funkcjonalności, rozszerzenia są, jak zawsze, twój najlepszy przyjaciel

func indexesOfSubset<T : Equatable>(objects : [T]) -> [Int] { 

    // Create storage for filtered objectsand results 
    var unusedObjects = objects 
    var result : [Int] = [] 

    // Enumerate through all objects in array 
    for (index, obj) in enumerate(self) { 

     // Enumerate again through all objects that has not been found 
     for x in unusedObjects { 

      // If we hit match, append result, remove it from usused objects 
      if obj as! T == x { 
       result.append(index) 
       unusedObjects = unusedObjects.filter({ $0 != x }) 
       break 
      } 
     } 
    } 

    // Get results 
    return result 
} 

Uwaga *: Prace nad Swift 1.2, jeśli chcesz kompatybilność z 1,1, wymienić! -> jak

14

W Swift 2.0 (Xcode 7.1b), można użyć

if let result = array.indexOf("Jason") 

podczas find(array, "Jason") jest przestarzała.

Powiązane problemy