Ad space (banner)
๐ŸฆSwift Lessons
Lesson 9 / 68

Classes (Object-Oriented Programming)

In this lesson you will learn the basics of object-oriented programming with Swift classes, so you can group data that shares the same characteristics. This is for anyone searching for "Swift class how to use".

class defines a class, and init is the special method used for initialisation. There is also struct, a value-type mechanism similar to a class, and choosing between class and struct to suit the job is characteristically Swift.

The sample code gives the Animal class the properties name and sound, initialises them with init(name:sound:), and builds a message in the speak() method. Setting the initial values in init lets the compiler catch any property you forgot to initialise.

A common stumbling block for beginners is the self keyword. To reach the object's own property from inside the initialiser you have to write self.name, and without that you get an error from the clash with the argument name.

In real-world development, choosing between class and struct (reference type or value type) is an important design decision in a Swift app.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)