Chapter    31

Classes

Use classes to define types in Swift that you want to use as objects. Like structures, classes give you a way of grouping related information and behavior together.

To define a Swift class, use the class keyword (see Listing 31-1).

Listing 31-1. Defining Classes

class Person {    var name: String = "Name"    var age:Int = 0    func profile() -> String {       return "I'm \(self.name) and I'm \(self.age) years old."    }}

In Listing 31-1, you defined a class named Person. Your Person class consists of a string for a person’s name and an integer for a person’s age.

When used like this in structures (Chapter 30) and classes, these variable and constant types are called properties.

Class Instances (Objects)

In Listing 31-1 ...

Get Swift Quick Syntax Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.