Welcome to the exciting world of Swift programming! Today, we're diving into one of the fundamental concepts - Methods. Let's get started! 🎯
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!
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! 💡
greet(name: "John") // Output: Hello, John!Swift has two types of methods:
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.
You can pass multiple parameters to a method.
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.Methods can also return a value, making them even more versatile.
func calculateArea(length: Double, width: Double) -> Double {
let area = length * width
return area
}
let area = calculateArea(length: 5, width: 10) // Output: 50Here, calculateArea method calculates and returns the area of a rectangle given its length and width.
What does the `->` symbol represent in a Swift method declaration?
Stay tuned for our next lesson on Methods in Classes! 🚀
Happy coding! 💻🔧🎉