• 20 heures
  • Moyenne

Ce cours est visible gratuitement en ligne.

Ce cours est en vidéo.

Vous pouvez obtenir un certificat de réussite à l'issue de ce cours.

J'ai tout compris !

Mis à jour le 04/02/2019

Discover class properties and methods

Connectez-vous ou inscrivez-vous gratuitement pour bénéficier de toutes les fonctionnalités de ce cours !

We’ve got the basic idea of objects now: defined classes with properties and methods. However, there are still some parts of our design that have been left out.

Remember, when we create a variable of a class, we say that we create an instance of a class. So, the properties and methods we defined so far are also called instance properties and instance methods.

Great! What else is out there?

There are also Class properties and methods and that’s what we are going to cover in this chapter.

Introducing class properties and methods

Class properties and methods apply to class in general.

Say, we have a Game class. A maximum of 4 people can play. When we create an instance of Game, we could have a variable (or a constant) as a part of it which stores the max players value. It’s not the end of the world, but that value applies to all instances of this game. And with this implementation, in order to access that value we'd have to create an instance of a class just to find out how many players can participate. Sounds inefficient :'(.

Declaring class properties and methods

The syntax for class properties and methods declaration is the same as for instance properties and methods, with an addition for the keyword  static before the declarations:

class ClassName {
    static var classVariable: Type
    static let classConstant: Type
    
    static func classMethodName() {
        // method logic
    }
}

Concretely, it looks like this when we declare ourGame class:

class Game {
    static let maxPlayers = 4
}

Utilizing static properties and methods

To access static properties or call static methods, we also use the dot notation. However, we use the class name itself, rather than a variable of that class:

ClassName.propertyName
ClassName.methodName()

If we use the Game example:

print("Only the chosen \(Game.maxPlayers) can play this game") // 4

Since those methods and properties are global and apply to the class as a whole, we don’t need to initialize anything.

In other words, in our game class example, we don’t have to create the object Game class just to find out how many players can play!

There are plenty of handy constants and methods available in existing objects in Swift. Here are a few examples:

Float.infinity // defines the largest number that can be stored as a float number
Float.pi // provides the value of pi

Formalizing the terms

Lastly, to formalize the terminology, according to Apple’s definitions, static (or class) properties and methods are called TYPE properties and TYPE methods.

To sum it up, these labels - class, static and type mean the same thing:

  • 'class properties' = 'static properties' =  'type properties' 

  • 'class methods' = 'static methods' =  'type methods' 

Fantastic! How is this beneficial to our project?

NeXTDestination progress

Let's review our original design:

NeXTDestination class design
NeXTDestination class design

Can you spot the elements that belong to the class level?

We've certainly got some properties in the Adventure class:

  • maxDestinations

  • totalBudget

  • returnCost

Now try to declare those on your own!

// Don't scroll just yet!





























class Adventure {
    // static properties
    static let maxDestinations = 5
    static let totalBudget = 10000.0
    static let returnCost = 800.0

    /* ... */
}

Let's think ahead. We'll need a pool of general entertainment elements we can choose from, so that we can later assign some of those to each destination as options during our visit.

A suitable solution for this is creating a static array variable -  generalOptions  -  that will contain a pool of ALL possible entertainment elements. From there, we create a static method -  generateGeneralOptions  - which will provide the elements for the new generalOptions variable. Since this data is related to the context of entertainment, we will position these new items within our Entertainment object. Try it on your own:

// Don't scroll just yet!



























class Entertainment {
    /* ... */
    
    static let generalOptions = Entertainment.generateGeneralOptions()

    static func generateGeneralOptions() -> [Entertainment] {
        return [Entertainment]()
    }
    
    /* ... */
}

For now, it returns an empty array, which is not suitable for our journey. We'll address that issue later in the course.

Great progress on design implementation!

Let's Recap!

  • Class properties and methods are declared with keyword  static  .

  • To access static properties or call static methods, we use the dot notation and instead of using a variable name of an instance, we use the class name.

  • As opposed to an instance  a property or instance method, a class property or method is used from the class name.

  • Class properties are particularly useful for defining constants for a class.

  • Class methods are particularly useful for defining specific initializations or managing multiple instances.

Exemple de certificat de réussite
Exemple de certificat de réussite