how to for loop increment in swift 4?

my for loop increment is not working properly.



import UIKit

class ViewController: UIViewController {

@IBOutlet var Label1: UILabel!

@IBOutlet var Label2: UILabel!

@IBOutlet var textField: UITextField!

@IBOutlet var Label3: UILabel!

let alert = "you are wrong"

let correct = "you are right"

let enWord = ["delever","warn","work","love"]

let dkWord = ["afleverer","advarer","arbejder","elsker"]

override func viewDidLoad() {

super.viewDidLoad()

Label2.text = enWord[0]

}

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

/

}

@IBAction func Clicked(_ sender: Any) {

let answer = textField.text

for i in stride(from: 0, to: 4, by: 1) {

Label2.text = enWord[i]

if (answer == dkWord[i]){

}

else {

print("next")

}

}

}

>how to for loop



That code smells severely outdated/not Swift 4.


Go here and look at 'for-in' loops, instead:


https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ControlFlow.html

what doesn’t work ?


you do nothing if == succeeds. What do you expect ?


a simpler form would be (even though stride is OK)


    @IBAction func clicked(_ sender: Any) {     // start func name with lowercase
        let answer = textField.text
        for i in 0..<4 {
        Label2.text = enWord[i]
        if (answer == dkWord[i]){
              // do something and probably return after
            }
            else {
                print("next")
            }
    }

Or you could avoid array indexing entirely:

for (en, dk) in zip(enWord, dkWord) {
    print(en, dk)
}

I’ve started writing my code this way because it means I don’t have to worry about accessing the array out of bounds. And once you start down this path you might think about using a higher-level algorithm (like

first(where:)
) rather than a vanilla
for
loop. For example:
guard let en = zip(enWord, dkWord).first(where: { $1 == answer })?.0 else {
    … handle the not found case …
    return
}
… handle the found case …

Alternatively, you could avoid the loop entirely by pre-processing

enWord
and
dkWord
into a dictionary that maps one to the other:
let dkToEn = Dictionary(uniqueKeysWithValues: zip(dkWord, enWord))

at which point you can search using a dictionary lookup:

guard let en = dkToEn[answer] else {
    print("-not found-")
    return
}
print(en)

The drawback to this last approach is that you don’t control the compare function so, for example, you can’t do a case insensitive compare (you could canonicalise

answer
before doing the lookup but that may not cover all the necessary edge cases).

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
how to for loop increment in swift 4?
 
 
Q