Swift Functions: Reuse Code Using Function, Return Value From Function, and Customize Parameter Label
Hi All, As I told in the previous articles that I have started a #100DaysOfSwiftUI challenge this is my learning from Day 7. where I have learned about Reuse code using functions in Swift and returning a value from functions, and customizing parameter labels. Let's go through it at once:
Reuse Code Using Functions
when we have written some code and we want to use it again and again, we should be putting that code inside a function. Function are just chunks of code you've split off from the rest of your program and given a name so you can refer to it easily.
Functions are designed to let us re-use code easily, which means we don't have to copy and paste code to get common behaviors. you could use them very rarely if you wanted, but honestly, there's no point they are wonderful tools for helping us write clearer, more flexible code.
the times where we should consider creating our functions:
- When we want to reuse the same functionality in many places. Using a function here means you can change code in a single place and changes will be updated wherever the function is used.
- Function is useful in breaking up a code. when we have a long function which can be hard to follow what is going on in my code. but if you break it up into small functions then it becomes easier to follow.
Let's see an example like this:
print("Welcome to my app!")
print("By default This prints out a conversion")
print("chart from centimeters to inches, but you")
print("can also set a custom range if you want.")
//Can be written like this using function
func showWelcome() {
print("Welcome to my app!")
print("By default This prints out a conversion")
print("chart from centimeters to inches, but you")
print("can also set a custom range if you want.")
}
Let's break that down...
- It starts with the func keyword, which marks the start of a function.
- Then we have the function name which will be used call whenever we want to use that functionality In our case it is showWelcome which can be anything but always provide a meaningful name so that you can understand what that function does by its name.
- then () which is used for collecting any parameter if we want to use for the code( I will explain it in while)
- finally, block of code inside curly brackets {} just like we had in Loops and conditions.
if you remember in the last posts we were using functionalities like count(), uppercased() in strings, etc. there are several functionalities are given by swift by default.
so now we defined the function then let's try to use that function:
showWelcome()
So what does this parenthesis do ? Well, that's where we add configurations options for our functions we get to pass in data the customizes the way the function works so the function becomes more flexible.
func showGreeting( name: String) {
print("Hello \(name), Welcome!)
}
showGreeting(name: "Coding Monkey")
showGreeting(name: "Coder")
So in the above code example while defining the function we are passing the variable name in parenthesis those are called arguments or parameters. those values can be used in our code to add flexibility to our code so depending on the name we are passing different messages will be printed.
Also, while calling the function with variables we have to provide the name of the parameter for which we are passing our value so that swift will know to which parameter it needs to assign that value to in function and also we have to make sure that when we call the function with parameter we are required to pass a value for those parameters otherwise Xcode will be throwing errors. and One last thing we have to maintain the same order in which the parameters are defined in the function definition. (don't worry much though the code will help you while using that function call by giving you the rest of the details you need to fill for that function call by giving suggestions you just have to pick the correct function you want to use. 😊)
We don't have any max limit on the numbers on how many parameters can be used in our code. when we have too many parameters in our function then we should consider that our function is doing too much work and try to split our current function into multiple small size functions so that code will be easier to follow.
Return Values From Functions
So earlier we created a function in which all the work was completed inside a function like printing the final output or showing some greetings. But as our code gets much complex we would be creating functions that would handle some complex logic for us to return a value which we get by applying that logic so that we can use that value in some other part of our code. Here's how we return a value from function:
func add(a: Int, b:Int) -> Int {
return a + b
}
So to get the value returned from our function by doing this our code:
- write an arrow using dash and > which will look like this: -> and then put the data type we want to return before our opening curly braces, which will tell swift to return a value of data type when the function is called.
- add a return statement in our code to send the data back. Also, keep in mind that once the return statement is called the function execution will be stopped there similar to the break we used in the loop which we learned in the last post.
So let's use that function we defined above:
let first = 10
let second = 20
let final = add(a: first, b: second)
print(final)
So by running this code we will be getting 30 printed in our console. one more example of using return value in function:
func rollDice() -> Int {
return Int.random(in: 1...6)
}
let result = rollDice()
print(result)
So this rollDice tells it must return an Integer, and the actual result is sent back with keyword return.
So by creating this method rollDice now we can change the number of sides just change the number by changing the end value in the range we are providing in that random function.
Important: When you say your function will return an Int, Swift will make sure it always returns an Int – you can’t forget to send back a value, because your code won’t build.
Return Multiple Values From Functions
when we want to return a single value from a function, we write an arrow then data type before our function opening braces. But there will be cases where want the multiple data to be returned such as when we sort the array or in case we pick some required values from an array, etc. Here is how we get the multiple values from function:
func getUser() -> [String] {
["Taylor", "Swift"]
}
let user = getUser()
print("Name: \(user[0]) \(user[1])")
So in place of the data type now we put the complex data type after the arrow we add. Depending on the use case we can use an array, set, dictionaries, or tuples as return data types.
Also if you see the in the function we defined we are missing the keyword return it is not a mistake but a functionality offered by Swift when we have a single line of code in our function which have a return type then result from that line of code will be sent back by default no need to add keyword return. (But I like to add keyword return so that I will know that I am sending some value that is a personal preference you can choose either of them 😊)
Tuples
Like arrays, dictionaries, and sets, tuples let us put multiple pieces of data into a single variable, but unlike those other options tuples have a fixed size and can have a variety of data types.
So from the last code example that we are expecting the first name and second name in order from the array. But as we know array doesn't know that we want the first value in the array is to a first name and the second value to be the last name, Also if we want to age in that array which can't happen as we know array holds singe type of data. The same goes for the Set which holds the single type of data and the set is known for creating its data storing order we can't expect a fixed order for our data to be in.
We can use Dictionaries but it comes with its problems which are we required to provide some default values just in case when no data is available for that key in dictionaries but we know for sure that we will be returning data from functions.
So as a solution for this problem we have tuples. Unlike Array we can store different types of data using dictionary type functionality and unlike a dictionary, we are expected to assign value to each key in the tuple and similar to set tuple can't have duplicates but it supports different types of data to store in it.
So let's use the tuple in our last code example:
func getUser() -> (firstName: String, lastName: String) {
(firstName: "Taylor", lastName: "Swift")
}
let user = getUser()
print("Name: \(user.firstName) \(user.lastName)")
let's break it down :
- Our return type is now (firstName: String, lastName: String), which is a tuple with 2 strings.
- Each string in tuple has a name. these aren't in quotes: they are specific names for each item in our tuple, as opposed to the kinds of arbitrary keys we had in dictionaries.
- inside the function, we send back a tuple containing all the elements we provided, attached to the names: firstName is being too "Tylor", etc.
- when we call getUser() we can read the values of the tuple using the key names: firstName, lastName, etc.
I know tuples seem awfully similar to dictionaries, but they are different:
- When you access values in a dictionary, Swift can’t know ahead of time whether they are present or not. Yes, we knew that user["firstName"] was going to be there, but Swift can’t be sure and so we need to provide a default value.
- When you access values in a tuple, Swift does know ahead of time that it is available because the tuple says it will be available.
- We access values using the user.firstName: it’s not a string, so there’s also no chance of typos.
- Our dictionary might contain hundreds of other values alongside "firstName", but our tuple can’t – we must list all the values it will contain, and as a result, it’s guaranteed to contain them all and nothing else.
We'll learn more about tuples as we keep learning about swift there will be plenty of cases where Tuple will come to our aide.
Customize Parameter Labels
We've seen how Swift developers like to name their function parameters because it makes it easier to remember what they do when the function is called. like this:
func rollDice(sides: Int, count: Int) -> [Int] {
// Start with an empty array
var rolls = [Int]()
// Roll as many dice as needed
for _ in 1...count {
// Add each result to our array
let roll = Int.random(in: 1...sides)
rolls.append(roll)
}
// Send back all the rolls
return rolls
}
let rolls = rollDice(sides: 6, count: 4)
In Swift when we're defining the parameter for a function we can actually add two names: one for use where the function is called and one for use inside the function itself. hasPrefix() uses this to specify _ as the eternal name for its a parameter which swifts the way of saying ignore this and causes others to be no external label for that parameter.
We can use the same in our code as well. like this:
func isUppercase(string: String) -> Bool {
string == string.uppercased()
}
let string = "HELLO, WORLD"
let result = isUppercase(string: string)
func isUppercase(_ string: String) -> Bool {
string == string.uppercased()
}
let string = "HELLO, WORLD"
let result = isUppercase(string)
So as we can see we are adding _ so that when we are calling the isUppercase() method we don't have to add the parameter label.
You already saw how we can put _ before the parameter name so that we don’t need to write an external parameter name. Well, the other option is to write a second name there: one to use externally, and one to use internally.
Here’s how that looks:
func printTimesTables(for number: Int) {
for i in 1...10 {
print("\(i) x \(number) is \(i * number)")
}
}
printTimesTables(for: 5)
So, Swift gives us two important ways to control parameter names: we can use _ for the external parameter name so that it doesn’t get used, or add a second name there so that we have both external and internal parameter names.
Conclusion
So I have learned on the Day 7 of 100 Days of SwiftUI that how to use Function in swift and customize the parameters in a function. and use case of both.
Also, let me know if any mistakes are done in this blog/write-up I have done for Day 7 learning so I can fix my mistakes and improve my understandings.
Thank you.