Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources
Properties and Methods in Swift

Properties and Methods in Swift

Introduction

In Swift, properties and methods are fundamental components of classes and structs. Properties are variables that belong to a class or struct, while methods are functions that define behaviors associated with those properties. This tutorial will guide you through the concepts of properties and methods, their types, and how to implement them in Swift.

Properties

Properties in Swift are used to store values. They can be categorized into two types: stored properties and computed properties.

Stored Properties

Stored properties are used to store constant or variable values as part of an instance. They can be either variables (declared with 'var') or constants (declared with 'let').

Example of Stored Properties

Here's how to define stored properties in a struct:

struct Person { var name: String var age: Int }

Computed Properties

Computed properties do not store values. Instead, they provide a getter and an optional setter to retrieve and set other properties or values.

Example of Computed Properties

Here’s how to define a computed property:

struct Rectangle { var width: Double var height: Double var area: Double { return width * height } }

Methods

Methods are functions that are associated with a particular type, allowing you to define actions that can be performed on instances of the type.

Instance Methods

Instance methods are called on instances of a type and can access properties of the instance using the 'self' keyword.

Example of Instance Methods

Here’s how to define an instance method:

struct Circle { var radius: Double func area() -> Double { return Double.pi * radius * radius } } let myCircle = Circle(radius: 5) let circleArea = myCircle.area()

Type Methods

Type methods are called on the type itself rather than on instances of the type. You define a type method using the 'static' keyword.

Example of Type Methods

Here’s how to define a type method:

class Math { static func square(_ number: Int) -> Int { return number * number } } let squaredValue = Math.square(4)

Conclusion

In this tutorial, we explored the concepts of properties and methods in Swift, including stored and computed properties, as well as instance and type methods. Understanding these fundamentals is essential for effective programming in Swift, allowing you to create more structured and organized code.