• 10 heures
  • Facile

Ce cours est visible gratuitement en ligne.

course.header.alt.is_video

course.header.alt.is_certifying

J'ai tout compris !

Mis à jour le 02/09/2019

Write the logic

We are approaching the finishing line, there's a bit left to do. In this chapter we will write the logic to generate our acting task!

Things get real!

So, we've got an acting task: "You are happy riding a horse!". It's a composition of three parts: 

  1. You are

  2. happy

  3. riding a horse

 The first part is constant - we will be addressing the user as "You are".

The other two parts are dynamic - generated by our app! Otherwise it wouldn't be fun to play :diable:! The first part defines an acting emotion and the second - an acting activity.

Let's come up with a number of examples for each and outline them in a diagram:

Each time we press 'ACT NeXT', the app will randomly select an item from each of the 2 lists and will compose a single meaningful sentence.

Let's list what we need to do in order to reach our goal: 

  1. Learn how to modify the text of a label

  2. Create our data lists 

  3. Select a random element from each list

  4. Combine them to create our sentence

Can you do it?

Of course you can!

Modifying the text of a label

We're a line of code away from accomplishing this!

Since we need to do it programmatically, we'll be using the outlet variable we created  actingTask

Remember, when we added a label to our interface, we changed the text directly in Attributes Inspector. Now we need to do it programmatically. To access a property of a label (or any other object) we are going to use the name of a variable that refers to it (actingTask)  followed by a dot (.) and followed by the name of a property we are interested in (text). And altogether: 

actingTask.propertyName

Sounds reasonable, but I do I know which property name to use?

There are different ways to figure it out.

1. Guess using Interface Builder

The captions of attributes listed in Interface Builder are usually the same or very similar to those available programmatically. It may not be the exact same one but it will definitely serve as a good hint to start!

In our case, it's captioned 'Text'- that might be it!

2. Let the Editor do the work - leverage autocompletion

We've discussed autocompletion earlier. It's just like Google search, as you start typing, the search engine suggests what it believes the most relevant. Xcode is using the same approach. We assumed the property name we are looking for might be 'text', let's verify:

Xcode property autocompletion
Xcode property autocompletion

As we type the first letter of our assumed property, we see a suggestion list pop up right below. Luckily, looks like we were right with our assumption. There's a property called text! And just to be sure, we can see that the description at the bottom of that pop-up states "The current text that is displayed by the label.". Sounds like the right thing!

What if you have NO CLUE what the property may be called? Or just want to explore what's out there?

You can scroll through the entire list of properties if you like!

3. Inspection

This is not exactly to figure out which property you need, but rather to confirm that you assuming the right thing. Inspection provides more details on an item you are inspecting.

To get the inspector pop-up, press and hold the alt key and click the word  text  for example:

Property details
Property details

 This pop-up presents some details. If you are still unsure or simply want to learn more, click Property Reference link, and you will be taken to the documentation page with complete details.

4. The documentation

If you just explored Property Reference option, you've already seen a part of documentation! 

And we already know how to access it - press and hold the alt key and click on an element of interest. This time, let's click on our label itself actingTask : 

Label details
Label details

If you click on the UILabel for example within the popup, you'll be taken to the UILabel developer documentation page:

Xcode documentation for UILabel
Xcode documentation for UILabel

It presents an extensive description of a label, its attributes, and properties. You can access their details by clicking a particular item on the tree-view on the left panel. This is also a good place to discover connections with other elements through exploring the links provided on the page.

5. Internet!

At all times, the internet is your best friend! Google in particular is handy at all time, there's even a coined term nowadays - Google it!. But seriously, use whichever search engine you prefer.

On a general note, if you can't find your problem described on the internet, there are only two reasons for it:

  1. The problem is extremely new. This is a very unlikely scenario in most cases. An exception could be, something just got released, you started using it immediately and it has a really annoying bug in it... Even then, likely someone already posted a problem, there may not be a solution to it just yet.

  2. There's something very silly in your code and you are looking for a solution for a problem that doesn't exist. Sorry to be blunt, this is a very likely scenario :ange: 

Can we change our text already?

We figured out the property name and, now, all we have to do is assign a new value to it (by the way, we can now remove our  print(...) function we used to test the action, we know it works and no longer need it):

actingTask.text = "This is a modified text of our label!"

Click the Run button (cmd + r) to launch the app, then click 'ACT NeXT' button, and here's what we expect to see:

We've modified the text of our label!
We've modified the text of our label!

Congrats! Let's move onto the next task.

Creating Data Lists

We need to store our emotions and activities. Each of them is a collection of elements: strings in particular. And we've learned that we store data in variables. One of the collection types in Swift is called Array. An array is an object that may contain any number of elements, a collection of elements (it can also be empty - contain 0 elements). An array is a collection of zero or more elements. 

To create an array, just use the brackets  []  and separate the elements with commas like this:

[element1, element2, element3]

Each element in our arrays will be text, we already know that text requires using surrounding quotation marks. Starting with emotions, our array will look like this:

["happy", "sad", "excited", "concerned", "surprised", "trusting", "worried", "in anticipation", "disappointed", "surprised", "frustrated"]

All good, except it's hanging in the air, and it needs a to become a variable.

var emotions = ["happy", "sad", "excited", "concerned", "surprised", "trusting", "worried", "in anticipation", "disappointed", "surprised", "frustrated"]

Where does it belong in our code?

It belongs with other variables we already have, in fact, only one so far, our label. Position your new emotions array right above the label and create an array for activities in the same fashion. Here's what we get:

class ViewController: UIViewController {
var emotions = ["happy", "sad", "excited", "concerned", "surprised", "trusting", "worried", "in anticipation", "disappointed", "surprised", "frustrated"]
var activities = ["swimming with dolphins", "planting trees", "sailing in the ocean", "reading a book", "riding a horse", "watching a movie", "riding a bike", "cleaning your house", "dining with friends", "running from a lion", "crawling in a desert"]
@IBOutlet weak var actingTask: UILabel!
@IBAction func generateActingTask() {
actingTask.text = "This is a modified text of our label!"
}
}

Let's Recap!

  • You can find out a property name in one of the following ways:

    1. Interface Builder by searching in the Attributes Inspector.

    2. Autocompletion - by attempting to partially type the name or looking through the whole list.

    3. Inspection by clicking on a word with the alt key pressed.

    4. By accessing the documentation:

      1. Through inspection pop-up

      2. Xcode menu: Window Menu-> Developer Documentation

      3. Shortcut shift + cmd + 0

    5. Searching on Internet (StackOverflow is recommended resource)

  • An Array is an object that allows to store a collection of elements.

  • To create an array, use the brackets and separate the elements with commas like this:

var myArray = [element1, element2, element3]
Et si vous obteniez un diplôme OpenClassrooms ?
  • Formations jusqu’à 100 % financées
  • Date de début flexible
  • Projets professionnalisants
  • Mentorat individuel
Trouvez la formation et le financement faits pour vous
Exemple de certificat de réussite
Exemple de certificat de réussite