top of page
Home: Blog2
Home: Instagram_Widget

Iterating over an Array using a for loop

Updated: May 8, 2020

As you're learning arrays and loops you will come to a point where you need to run a loop i.e iterate over a loop to get something done. As you would know by now the idea behind using a loop is to repeat code until a condition is false.


The mechanics worth understanding is that in a for loop each iteration of the loop (or a run over the loop) is assigned to a temporary constant. So once the condition is met you may want to kind of stop the loop from running. We do this by inserting break into the code.


In the example below we use the for loop to run the provided userNames against the registeredUsers array.


While there a few variants of loops in this post we are focusing on the for loops. Note that for loops are different from while loops. With a for loop you aren't checking each time to check if a conditions is true. Instead the loop will run a certain number of times depending on the number of element in the sequence.

var registeredUsers: [String] = []
var registeredPassword: [String] = []

func addUsers(addName: String, addPassword: String) -> String {
    registeredUsers.append(addName)
    registeredPassword.append(addPassword)
    return "user successfully added"
}

addUsers(addName: "tom", addPassword: "tweetybird")
addUsers(addName: "jill", addPassword: "jackandjill")
addUsers(addName: "james", addPassword: "mynameisbond")

func userLoginChecking(userNames: String){
    for user in registeredUsers {
        if user == userNames {
            
            print ("The user \(userNames) exists")
            break
        }
        else  {
            
            print("The user \(userNames) does not exist")
           
        }
    }
    
}

userLoginChecking(userNames: "james") // in the array

so as the userNames are looped over the registeredUsers array the for loop checks against each value in the array and then prints either one of the two sentences :


The user james does not exist
The user james does not exist
The user james does exists

Now if you just wanted to check if the userName existed in the array and just get a boolean value you could create another function and get the response.



func userLogin(yourUsername: String)-> Bool {
 for _ in registeredUsers {
 if registeredUsers.contains(yourUsername) {
 return (true)
 } else {
 return (false)
 }
}
 return (true)
}

// actually you dont need the for _in you can comment it out and .contains  by itself return the boolean value.

userLogin(yourUsername: "tom")
userLogin(yourUsername: "felix")





Comments


Home: Subscribe

©2019 by CodingWithSuj. Proudly created with Wix.com

bottom of page