Classes
Model everyday objects using classes!
StartKey Concepts
Review core concepts you need to learn to master this subject
Swift Class
Instance of a Class
Class Properties
init()
Method
Inheritance
Overriding
Reference Types
Swift Class
Swift Class
// Using data types:
class Student {
var name: String
var year: Int
var gpa: Double
var honors: Bool
}
// Using default property values:
class Student {
var name = ""
var year = 0
var gpa = 0.0
var honors = false
}
A class is used to programmatically represent a real-life object in code. Classes are defined by the keyword class
followed by the class name and curly braces that store the class’s properties and methods.
Classes
Lesson 1 of 1
- 1So far, we’ve used several data types, including Int, Double, String, and Bool. We’ve even created our own “type” using structs to make blueprints and templates for objects in our program. Besides…
- 2Just like structures, we can use classes to model everyday objects. And the syntax looks awfully similar. Here’s the basic syntax for creating a class: class Name { } The class keyword follo…
- 3To refresh, a class is simply a template to create objects. The term “object” is often used to refer to an instance of a class. So for example, a building blueprint is a class and each house is an …
- 4In the previous exercise, we’ve supplied our instances’ properties with default values. However, if we know that our class instances vary a lot from one to another, we can include an init() method …
- 5In the previous exercises, we’ve defined a class, created instances, and added an init() method. But all these concepts were the same in structures. So now we have to ask, “how are classes differen…
- 6To continue the conversation on inheritance, a subclass can provide its own custom implementation of a property or method that is inherited from a superclass. This is known as overriding. To ove…
- 7Another one of the biggest main distinctions between structures and classes is that: - Structures are value types - Classes are reference types A value type is a type whose value is copied when i…
What you'll create
Portfolio projects that showcase your new skills
How you'll master it
Stress-test your knowledge with quizzes that help commit syntax to memory