• 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

Finish the application

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

Welcome to the final chapter of this course! Here we'll complete our app! 

Back to reality, here's our unfinished to-do list:

  1. Learn how to modify the text of a label (Done!)

  2. Create our data lists (Done!)

  3. Select a random element from each list

  4. Combine them to create our sentence

Two more to go!

Selecting a random element

Let's split this task into two subtasks:

  1. Access an element

  2. Select a random element

1. Access an element

To be able to access an element we need to learn a little bit more about arrays. 

Specifically, that an array is a collection of indexed elements. Meaning that each element is associated with a number. This number is called Index. 

Knowing that, we now can access elements in our arrays. For example, to get a 'happy' emotion (first element), we need to request an element at index 0. To implement this request in code we need to specify the desired index in square brackets  [] after an array name:

emotions[0]//happy

You can test this by usingprint()  function (add this temporarily to  generateActingTask() function):

print(emotions[0])

Launch the application, click on the button "ACT NeXT" and you should see in the console:

happy

Experiment with indexes on your own to get comfortable using this approach.

2. Select a random element

Next thing to figure out is how to make it random. If we generate a random index, the element we request at that index can be considered random. 

Do I have to do all the math?

In Swift ether's a function for that:  arc4random_uniform. It generates a random number in a range from 0 to a number we specify. It takes a single parameter - the upper number of the range. You can test it by adding it to your  generateActingTask() function and click a few times to observe the random effect:

print(arc4random_uniform(10))

In our example, we'll get a number between 0 and 9 (inclusive), means 9 will be the maximum we can get and not 10.

Say, if we have 5 elements in our array, the last valid index will be 4. Therefore our range is 0 to 4. In order to request this range from our randomization function, we need to supply an upper limit, which is maximum index + 1 = 5.

 Basically, we need to supply the number of elements in our array:

arc4random_uniform(arrayCount)

And how do we get that count?

 Remember object properties and the guess work we practiced earlier? Let's flex our brain muscle and try   count . As before, use a dot to access it:

emotions.count//11

Everything is ready to generate a random index:

var emotionRandomIndex = arc4random_uniform(emotions.count)

And finally accessing a random element:

var randomEmotion = emotions[emotionRandomIndex]

After applying the logic above to both, emotions and activities, our function should look like this:

@IBAction func generateActingTask() {
//generate random emotion
var randomEmotionIndex = arc4random_uniform(emotions.count)
var randomEmotion = emotions[randomEmotionIndex]
print(randomEmotion)
//generate random activity
var randomActivityIndex = arc4random_uniform(activities.count)
var randomActivity = activities[randomActivityIndex]
print(randomActivity)
//modify the label
actingTask.text = "This is a modified text of our label!"
}

You can now test the app and observe random emotions and activities appear in the console.

Yes, it works! But why my code has yellow marks all over?

Those are warnings. Means, we did ok, just not perfectly :euh:.

Dealing with issues in Xcode

Xcode is a sophisticated software. It is on a mission to serve you at any moment.

As you type, Xcode validates your code and provides the most relevant feedback - whether it's all good, incorrect (Error) or can be improved (Warning).

Errors

Errors are marked with red icons (). They prevent your code from executing and must be fixed. If you click the usual Run, you'll get a message 'Build Failed'.

Warnings

Xcode wants your code to be perfect. In fact, it's just selfish and doesn't want to compensate for your imperfections when translating your writing into machine code. Those are warnings, they are marked with a yellow icon ( ).

Errors and warnings are called issues.

Warnings are minor errors that do not prevent your code from running. Sometimes it may be Xcode suggestions to improve the quality of your code. Sometimes, Xcode warns you that your code is dangerous, that is, it is easily susceptible to crash.

Viewing issues

To view your project's issues switch to the 'Issue Navigator' tab on Navigator panel (the one on the left):

Xcode Issue Navigator
Xcode Issue Navigator

This list contains all the issues in all files of your project. If you click on one, Xcode will open the file containing selected issue and will bring you to the line of code with that issue.

At the top of Xcode, there's a panel that also indicates the number of issues in your project:

 

Troubleshooting

Troubleshooting, or resolving the issues, can via done in two ways (and their combination):

  1. The error icon contains an exclamation mark. Read the description and if you can not find the solution alone, I suggest you copy the description into Google. Someone probably encountered this error and a solution was found.

  2. The error icon contains a period. This is the case with the warnings you have. In this case, Xcode is able to solve the error itself.

In this second case, just click on the icon (here the yellow triangle) to see the solution Xcode proposes.

The description is in blue and your code is changed (in gray). If you do not confirm, your code will remain unchanged, but it allows you to preview what it would mean if you accepted the change.

Then just enter  Xcode to apply the change.

We shall now see what our error means.

What are Constants in Swift?

Similarly to a variable, a Constant is also a named value of a particular type, with the difference that, once assigned, it cannot change its value. 

Variables can change their value (they vary) - they are mutableConstants cannot change their value (they remain constant) - they are immutable.

And one more fancy definition: a constant is an immutable variable.

So, how does the Xcode know the difference? 

By the declaration. For variables we are using the keyword  var, and for constants we have to use the keyword  let:

var myVariable = 0 // can be modified
let myConstant = 0 // cannot be modified

Then, if we try to modify those two:

myVariable = 1
myConstant = 1 // Cannot assign to value: 'myConstant' is a 'let' constant

Xcode will be content with the first line. However, it will generate an error for the second line, explaining that we cannot assign the value as 'myConstant' is a constant.

Got it. But what's the purpose of having variables that cannot be modified? 

Often we will need a variable to just store a data, but not necessarily to modify it. Storing data requires memory allocation. And storing mutable data requires more memory than immutable. 

Why is that?

In simple terms, imagine memory as a tall dresser with many drawers. To store letters for example, we need one drawer per letter. For example, to store "Hello!", we need 6 drawers in a dresser:

var message = "Hello!"

The memory would look like this:

Since it's a variable, its value may change. Say, it becomes: "Hello, my friend!". In this case we need more drawers to store it. But what if drawers next to it are already taken? To accommodate for this, each variable takes more space than it needs originally to accommodate future variations. So that our original variable will look more like this in memory:

Basically, using variables when we know the value won't change, we are unnecessarily reserving memory resources that could be utilized elsewhere. 

Let's follow best practices and use constants wherever possible!

This is exactly what Xcode is suggesting:

Variable 'randomEmotionIndex' was never mutated; consider changing to 'let' constant

Xcode recognized that we never change any of the 4 variables. We assign values to them and then just use them as they were originally created. That includes our arrays, we only need to access their elements, that makes it 6.

To eliminate the warnings and improve the code, let's go ahead and convert all 6 variables to constants by replacing the keyword  var  with the keyword  let.

We've been experimenting a lot with various pieces of code in out controller file - adding, removing, testing, fixing... Just to make sure we are on the same page, here's what the current state of our code should be:

import UIKit
class ViewController: UIViewController {
let emotions = ["happy", "sad", "excited", "concerned", "surprised", "trusting", "worried", "in anticipation", "disappointed", "surprised", "frustrated"]
let 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() {
//generate random emotion
let randomEmotionIndex = Int(arc4random_uniform(UInt32(emotions.count)))
let randomEmotion = emotions[randomEmotionIndex]
print(randomEmotion)
//generate random activity
let randomActivityIndex = Int(arc4random_uniform(UInt32(activities.count)))
let randomActivity = activities[randomActivityIndex]
print(randomActivity)
//modify the label
actingTask.text = "This is a modified text of our label!"
}
}

Great job! We are so close to achieving our goal - just one more step!

Composing an Acting Task

All that's left is to combine the three parts of content into a meaningful phrase. In order to do that we are going to use a convenient operation called concatenation. It's applicable to the variable of String type (another common variable type).

For example:

var forecast = "Sunshine " + "and " + "blue sky!"
print(forecast) // Xcode will output in console: Sunshine and blue sky!

Now we have absolutely everything to compose a phase for the new acting task:

let newActingTask = "You are " + randomEmotion + " " + randomActivity + "!"

And finish our function by assigning it to the text property of the label:

actingTask.text = newActingTask

Let's do some clean-up and remove print functions, we don't need them anymore.

All done! Here's the complete function:

@IBAction func generateActingTask() {
//generate random emotion
let randomEmotionIndex = Int(arc4random_uniform(UInt32(emotions.count)))
let randomEmotion = emotions[randomEmotionIndex]
//generate random activity
let randomActivityIndex = Int(arc4random_uniform(UInt32(activities.count)))
let randomActivity = activities[randomActivityIndex]
//modify the label
let newActingTask = "You are " + randomEmotion + " " + randomActivity + "!"
actingTask.text = newActingTask
}

Is that it for real?

Indeed! Launch the app and tap the button! :magicien: Each time a new acting task will be generated!

Congratulations! You've just completed your first iPhone application! 

 

You make people happy!

Let's Recap!

  • To access the elements of an array, use the index with the following syntax:

  • var myElement = myArray[index]
  • To get the number of elements in an array, use thecount  property.

  • Xcode identifies 2 types of issues:

    • Errors: they prevent the app from executing

    • Warnings: they don't prevent the app from running, they are rather improvements that should be made to the code

  • You should aim to resolve errors and warnings as soon as they occur.

  • To concatenate 2 or more strings, use the plus sign:  +.

Final Word

First and foremost - congratulations! You've just completed a fully functional entertaining iPhone application from scratch! This already entitles you mildly call yourself an iOS developer

Along the way, you discovered the primary development tool - Xcode, its core capabilities and how operate within the development environment.

You've also learned the basics of programming with Swift language, figured out fundamental concepts of a programming language: variables and functions and their specifics in Swift.

With that in mind, I encourage you to continue learning iOS development and move on to the next courses entirely dedicated to Swift and Object-Oriented Programming.

And to compensate for the absence of a usual minion in the beginning of this chapter, here's one:

Until next time!
Until we meet next time!

 

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