O'Reilly logo

Swift Quick Syntax Reference by Matthew Campbell

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required