Swift 3找到具有重复值的[Int]数组的正确索引

时间:2017-05-10 09:56:37

标签: swift

我正在寻找一种方法来找到具有重复值的[int] -array的正确索引。我想要认识到循环中的值已经发生了变化。循环计数器变量是不可能的,因为评估是在另一个线程中。

In [8]: u+v
Out[8]:
a    4
a    4
a    4
a    4
b    4
b    4
b    4
b    4
c    4
c    4
c    4
c    4
d    4
d    4
d    4
d    4
e    4
e    4
e    4
e    4
dtype: int64

Gerriet解决:

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)

2 个答案:

答案 0 :(得分:0)

所以这是我的评论作为答案。您可以使用枚举:

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

这样你就可以立即获得正确的索引(独立于重复索引)。

答案 1 :(得分:-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)")
            }
        }
    }