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 are the most basic type of properties. They store values that are defined when an instance of the class or structure is created.
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.
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.
Unlike stored properties, Computed properties do not store actual values. Instead, they provide a way to compute and return values on demand.
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.0In 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! š¤