Swift Tutorials: Adding Methods 🚀

beginner
20 min

Swift Tutorials: Adding Methods 🚀

Welcome to the exciting world of Swift programming! Today, we're diving into one of the fundamental concepts - Methods. Let's get started! 🎯

What are Methods in Swift? 📝

Methods (also known as functions) are blocks of code that perform a specific task or series of tasks. In Swift, methods help us organize and reuse our code, making our programs more efficient and maintainable.

Let's create our first method!

swift
func greet(name: String) { print("Hello, \(name)!") }

Here, greet is our method that greets a person with their name. The name is a parameter, and print is a built-in method for printing the output. Let's use it! 💡

swift
greet(name: "John") // Output: Hello, John!

Types of Methods in Swift 📝

Swift has two types of methods:

  1. Functions (as shown above)
  2. Methods in a Class or Struct

While functions can be defined globally or within a file, methods are always associated with a specific class or struct. We'll cover methods in classes later in this tutorial.

Methods with Multiple Parameters 💡

You can pass multiple parameters to a method.

swift
func greetWithAge(name: String, age: Int) { print("Hello, \(name)! You are \(age) years old.") } greetWithAge(name: "Jane", age: 25) // Output: Hello, Jane! You are 25 years old.

Returning a Value from a Method 📝

Methods can also return a value, making them even more versatile.

swift
func calculateArea(length: Double, width: Double) -> Double { let area = length * width return area } let area = calculateArea(length: 5, width: 10) // Output: 50

Here, calculateArea method calculates and returns the area of a rectangle given its length and width.

Quiz 💡

Quick Quiz
Question 1 of 1

What does the `->` symbol represent in a Swift method declaration?

Stay tuned for our next lesson on Methods in Classes! 🚀

Happy coding! 💻🔧🎉