SwiftUI_visionOS_Note

function

Jan 9, 2024
5 min read|
  • Functions are chunks of code we’ve split off from the rest of program
  • given a name so we can refer to them easier

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

Let’s say we want to print this lines of string on the screen. It’s okay to use if this is on only one screen. But what if it’s on multiple pages?

  • Function allows us to pull out the code, give it a name, and run it whenever and whereever.
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.")
}
swift

() are used with functions.

When we create a function, () are used.

or, When we call the function: ask swift to run the code

showWelcome()
swift

() are known as the function’s call site: “a place where a function is called”

We add configuration options for our functions

We get to pass data that customizes the way the function works

let number = 139

if number.isMultiple(of: 2) {
	print("Even")
} else {
	print("Odd")
}
swift

isMultiple(of:) If it didn’t allow any kind of customization in call site, what is it multiple of?

Yes, there are functions that doesn’t require configuration options, like isOdd() or isEven().

By writing (of: 2) , we can check for multiple of any other numbers.

We were rolling virtual dice in Loop, While & Skip tutorial with a code like this:

let roll = Int.random(in: 1...20)
swift

by writing (in: 1...20), we control over the range of our random numbers.

without it, random integer of what?

func printTimesTables(number: Int){
	for i in 1...12{
		print("\(i) x \(number) is \(i * number)")
	}
}

printTimesTables(number :5)
swift

(number: Int) inside the parentheses is called parameter.

  • Inside the (), number: is used like any other constant contains Int
  • We need to write the parameter name as part of the function call.

func printTimesTables(number: Int, end: Int){
	for i in 1...end{
		print("\(i) x \(number) is \(i * number)")
	}
}

printTimesTable(number: 5, end: 20)
swift
  • Naming gets more important when we have multiple parameters.

printTimesTable(number: 5, end: 20)
swift

(number: 5, end: 20) inside this parentheses is called argument.

We have both parameters and arguments: one is a placeholder the other is an actual value, so if you ever forget which is which just remember Parameter/Placeholder, Argument/Actual Value.

  • But we use “parameter” for both, or “argument” for both. it doesn’t matter.

When we run the fuction, we have to write the argument in order they were listed when it was created.

Return values from functions

Functions can also send data back.

import Cococa includes a variety of mathematical functions, sqrt()

sqrt() function accepts one parameter (Int), it will do the work and send back the data

import Cocoa

let root = sqrt(169)
print(root)
swift

  • If I want to return my own value from a function need to do two things
    1. Write an arrow then a “data type” before opening brace, telling Swift what kind of data will get sent back
    1. Use the return keyword to send back data

func rollDice() -> Int {
	return Int.random(in: 1...6)
}

let result = rollDice()
print(result)
swift
  • Function must return an integer func rollDice() -> Int {}
  • The actual value is sent back with the return keyword.

Now we can use rollDice() in lots of places across the program.

Do two strings contain the same letters, regardless of their order? This function should accept two string parameters, and return true if their letters are the same – so, “abc” and “cab” should return true because they both contain one “a”, one “b”, and one “c”.

Hint: use sorted() to get a new string back with all the letters in alphabetical orders

Hint: use == to compare them to see if their letters are the same

Hint: make function names areLettersIdentical

func arelettersIdentical(string1: string, string2: string) -> Bool {
let first = string1.sorted()
let second = string2.sorted()
return first == second
}
swift

Let’s break down

  1. It creates a new function called areLettersIdentical()
  1. The functions accepts two string parameters (string1: string, string2: string)
  1. The function says it returns a Bool, at this point we must return either true of false.
  1. Use == to compare strings → if they are same, it will return true else false.

We can skip those temporary constants first and second and just compare the results of sorted() directly.

func areLettersIdentical(string1: String, string2: String) -> Bool {
	return string1.sorted() == string2.sorted()
}
swift

If there is only one line of code, we can remove return

func areLettersIdentical(string1: String, string2: String) -> Bool{
	string1.sorted() == string2.sorted()
}
swift

import Cocoa

func pythagoras(a: Double, b: Double) -> Double {
 let c = (a*a) + (b*b)
let result = sqrt(c)
    return result

}

let c = pythagoras(a: 3.4, b: 8.5)
print(c)
swift

So, that’s a function called pythagoras(), that accepts two Double parameters and returns another Double. Inside it squares a and b, adds them together, then passes that into sqrt() and sends back the result.

That function can also be boiled down to a single line, and have its return keyword removed – give it a try.

import Cocoa

func pythagoras(a: Double, b: Double) -> Double {
    return sqrt(a * a + b * b)
}

let c = pythagoras(a: 2.0, b: 3.0)
print(c)
swift

Return multiple values from functions

Write an arrow and a data type to return a single value from a function

func isUppercase(string: String) -> Bool {
	string == string.uppercased()
}
swift

Use an array to return two or more values from a function

func getUser() -> [String] {
	("Taylor", "Swift")
}

let user = getUser()
print("Name: \(user[0]) \(user[1])")
swift

It’s hard to remember what user[0] and user[1] are.

  • It can be problematic to adjust the data in that array in future

We can use #dictionary , but it has its own problems.

func getUser() -> [String: String] {
	[
		"firstName": "Taylor",
		"lastName": "Swift"
	]
}

let user = getUser()
print("Name: \(user["firstName", default: "Anonymous"]) 
\(user["lastName", default: "Anonymouse"])")
swift
  • We still need to provide default value default: "Anonymous"

We can use a solution in the form of #tuples.

Tuples let us put multiple pieces of data into a single variable

Unlike those other options tuples have a fixed size and can have a variety of data types.

func getUser() -> (firstName: String, lastName: String) {
	(firstName: "Taylor", lastName: "Swift")
}

let user = getUser()
print("Name: \(user.firstName) \(user.lastName)")
swift
  1. Return type is now (firstName: String, lastName: String), a tuple containing two strings.
  1. Names in tuple aren’t in quotes. Opposed to the kind of arbitrary keys in dictionary.
  1. Send back a tuple containing all the elements we promised. (firstNmae: "Taylor", lastName: "Swift)
  1. Can read the tuple’s values using the key name when we call getUser().

Tuple seems similar to dictionaries, but they are different.
1. In a dictionary, we have to provide a default value because Swift can’t be sure if the value is going to be there.
2. Swift knows ahead of time that values in tuple will be always available.
3. We access values using
user.firstName, which isn’t string, so there’s no chance of typos.
4. Dictionary might contain hundreds of other values alongside
"firstName" but tuple can’t

There are three other things it’s important to know when using tuples.

  1. We don’t need to repeat names when using return, because Swift already know the names we are giving each item in tuple.
func getUser() -> (firstName: String, lastName: String) {
	("Taylor", "Swift")
}

let user = getUser()
print("Name: \(user.firstName) \(user.lastName)
swift

  1. Sometimes, we’ll find given tuple’s elements don’t have names. We can access the elements using numerical indices.
func getUser() -> (String, String) {
	("Taylor", "Swift")
}

let user = getUser()
print("Name: \(user.0) \(user.1)")
swift

The document provides eight key pieces of advice for those starting their programming journey: 1) Technology will change, so don't get stuck on one language or platform. 2) You won't remember everything you learn, and that's okay. 3) A computer science degree isn't necessary, but understanding CS fundamentals is important. 4) Continuous learning is part of the job. 5) Learn how to learn effectively. 6) A basic understanding of mathematics can be beneficial. 7) Resilience is crucial in overcoming challenges. 8) Programming involves more than just coding; interpersonal skills are also important. A bonus tip suggests investing in a mechanical keyboard.

Subscribe to our newsletter

Get the latest news and updates from our team