0
0
Swiftprogramming~30 mins

Class declaration syntax in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Class declaration syntax
📖 Scenario: You are creating a simple app to keep track of pets in a pet store. Each pet has a name and an age.
🎯 Goal: Build a Swift class called Pet with properties for name and age.
📋 What You'll Learn
Create a class named Pet
Add a property name of type String
Add a property age of type Int
Create an instance of Pet with name "Buddy" and age 3
Print the pet's name and age
💡 Why This Matters
🌍 Real World
Classes help organize data and behavior for real-world objects like pets, users, or products in apps.
💼 Career
Understanding class syntax is essential for building apps in Swift, especially for iOS development.
Progress0 / 4 steps
1
Create the Pet class with properties
Create a class called Pet with two properties: name of type String and age of type Int. Do not add any methods yet.
Swift
Need a hint?

Use the class keyword to create a class. Declare properties with var and specify their types.

2
Add an initializer to the Pet class
Add an initializer init(name: String, age: Int) to the Pet class that sets the name and age properties.
Swift
Need a hint?

Use init to create a constructor. Use self to refer to the current object's properties.

3
Create an instance of Pet
Create a variable called myPet and assign it a new Pet object with name set to "Buddy" and age set to 3.
Swift
Need a hint?

Use the class name Pet followed by parentheses with arguments to create an object.

4
Print the pet's name and age
Print the name and age of myPet using print. Format the output exactly as: Buddy is 3 years old.
Swift
Need a hint?

Use string interpolation with \(variable) inside the print statement.