Swift Tutorials: Properties (Stored, Computed) šŸš€

beginner
19 min

Swift Tutorials: Properties (Stored, Computed) šŸš€

Welcome to our Swift Properties tutorial! Today, we'll delve into one of the fundamental building blocks of Swift classes and structures - Properties. šŸ“

Properties define characteristics of your custom types (classes and structures). In this lesson, we'll explore two types of properties: Stored and Computed.

Stored Properties šŸŽÆ

Stored properties are the most basic type of properties. They store values that are defined when an instance of the class or structure is created.

swift
struct Person { var name: String var age: Int } let john = Person(name: "John", age: 25)

In the above example, name and age are stored properties of Person structure. šŸ’” Pro Tip: Use var to create mutable properties and let for constants.

Quiz

Question: What is the data type of name and age in the above example?

A: String and Int B: Number and Age C: Variable and Constants Correct: A Explanation: The data type of name is String and age is Int.

Computed Properties šŸš€

Unlike stored properties, Computed properties do not store actual values. Instead, they provide a way to compute and return values on demand.

swift
struct Point { var x: Double, y: Double var magnitude: Double { return sqrt(x*x + y*y) } } let p1 = Point(x: 3.0, y: 4.0) print(p1.magnitude) // Output: 5.0

In the above example, magnitude is a computed property that calculates the length of a vector using Pythagorean theorem.

Stay tuned for more Swift tutorials, where we'll dive deeper into the world of Swift programming!

šŸ“ Note: Don't forget to check out our upcoming lessons on methods, enums, and more! Happy coding! šŸ¤–