2017-05-10 10 views
0

私は、重複する値を持つ[int]配列の正しいインデックスを見つける方法を探しています。私は、ループ内の値が変化していることを認識したい。評価が別のスレッドにあるため、ループカウンター変数は不可能です。Swift 3重複する値を持つ[int]配列の正しいインデックスを探します。

var arrayInt = [1,2,2,3] 
var arrayIndex : Int? 
var currentStep = 0 

for i in arrayInt 
{ 
    arrayIndex = arrayInt.index(of: i) 
    print("Index \(arrayIndex)") 
    currentStep += 1 // Is not possible 

    for numbers in 1...i{ 

     DispatchQueue.global().asyncAfter(deadline: .now() + .seconds(1 + currentStep)) { 
      // prints always "4" becauses its at the executen time the value "4", which is plausible 
      print("CurrentStep \(currentStep)") 
     } 
    } 
} 
//Prints: 
//Index Optional(0) 
//Index Optional(1) 
//Index Optional(1) // must be 2 
//Index Optional(3) 

Gerrietによって解決:

var arrayInt = [1,2,2,3] 
var currentStep = 0 

for (currentStep,i) in arrayInt.enumerated(){ 
    for numbers in 1...i{ 
    DispatchQueue.global().asyncAfter(deadline: .now() + .seconds(1 + currentStep)) { 
     print("CurrentStep \(currentStep)") 
    } 
    } 
} 
//Prints: 
//CurrentStep Optional(0) 
//CurrentStep Optional(1) 
//CurrentStep Optional(2) 
//CurrentStep Optional(3) 
+0

どういう意味ですか?配列の重複値のインデックスを見つけるか?右? – Vahid

+0

わかりませんが、私は理解していますが、arrayInt.enumerated(){ のprint( "Index \(index):\(value)")のfor(index、value) 。そうすれば、すぐに正しいインデックスを得ることができます(重複とは無関係)。 – Gerriet

+0

どのように簡単に動作しますか?ありがとうございました – ZombieIK

答えて

-1

ねえコードの下に試してみてくださいあなたのために動作します:

var arrayInt = [1,2,2,3] 
    var arrayIndex : Int? 
    var currentStep = 0 

    for i in 0..<arrayInt.count{ 
     //here i is Your index 
     arrayIndex = i 
     print("Index \(arrayIndex)") 
     currentStep += 1 // Is not possible 

     for numbers in 1...arrayInt[i]{ 

      DispatchQueue.global().asyncAfter(deadline: .now() + .seconds(1 + currentStep)) { 
       // prints always "4" becauses its at the executen time the value "4", which is plausible 
       print("CurrentStep \(currentStep)") 
      } 
     } 
    } 
0

だからここに答えとして私のコメントです。

for (index,value) in arrayInt.enumerated() { 
    print("Index \(index) : \(value)") 
} 

このようにして、正しいインデックスをすぐに得ることができます(重複しないように)。

関連する問題