Search code examples
iosarraysswift4

Swift 4 how to count the distance between 2 elements in an array with all unique elements?


I'm trying to create a simple array in my apps. May I know how to calculate distance between 2 elements in my array? Example:-

I have an array as below:-

var aryNumberList = ["7","4","8","6","9","1"]

if i get my textfield A = 7 and textfield B = 9 So my expected output is 4

if i get my textfield A = 6 and textfield B = 1 So my expected output is 2

if i get my textfield A = 1 and textfield B = 6 So my expected output is 4 (** will continue from begin)

Your help is appreciated! Thank you.


Solution

  • var positionA = 0 // declare as global variable
    var positionB = 0 // declare as global variable
    
    for i in 0 ..< aryNumberList.count  {
    
        if Int(aryNumberList[i]) == textfieldA.text {
    
                positionA = i
        }
    
        if Int(aryNumberList[i]) == textfieldB.text {
    
                positionB = i
        }
    }
    
    if positionA > positionB {
    
        print("** will continue from begin")
    
    }else {
    
        var distance = positionB - positionA
    
        print("\(distance)")
    }