top of page
Home: Blog2
Home: Instagram_Widget

For loops in Swift

Updated: May 16, 2020

One of the most common challenges a novice programmer has to overcome is to understand the concept of loops. So why loops? Well as you learn coding you will realise that there is a need to avoid repeating your code when you need to "loop" through a set of conditions to find a specific value or compute a specific output. There are a few different ways to loop through and in this post I will go through the basics of the for-loop..


Using the same case study which I used in my functions article, lets explain the concept of loops using the construct of the userName and registeredPassword for a simple application and lets assume the following :


  1. There are already a set of registered users who have already setup their userName and registeredPassword which has been stored in your app.

  2. Now that your user is going to login to the app, they will enter the userName and registeredPassword which the app then needs to quickly validate and then take an action to either block the user from logging in or grant them the access.


ree

So you will start in Xcode by writing a simple function to check if the userName exists. using the construct of a for-loop .


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")


//for loop in the function

func userLoginCheck(userName: String){
 for user in registeredUsers {
 user == userName
return
}
}
// run the function and it will loop over the entire registeredUsers array
userLoginCheck(userName: "james")

There is a lot more to learn for me on this. Stay tuned for more updates and better examples as I push through this segment in the coming weeks.





Comments


Home: Subscribe

©2019 by CodingWithSuj. Proudly created with Wix.com

bottom of page