Start learning free

LESSON 5 OF 415 · WELCOME TO SWIFT

Syntax Errors in Swift

Lesson

TL ; DR:

  • Syntax errors are mistakes in the use of the Swift language, analogous to spelling or grammar mistakes in a language like English. For example:


  • Omitting quotes when working with strings:

    print("Welcome!)
    

  • Omitting parentheses when using the print function:

    print("Let's code!"
    

  • When Swift encounters a syntax error, the compiler reports an error and your program does not run.




Full lesson:

Humans are prone to making mistakes. Humans are also typically in charge of creating computer programs. To compensate, programming languages attempt to understand and explain mistakes made in their programs.

Here are two common errors that we encounter while writing Swift code:


The syntax error:

Syntax errors are mistakes in the use of the Swift language, and are analogous to spelling or grammar mistakes in a language like English. For example, the sentence "Would you some tea?" does not make sense – it is missing a verb.

Syntax error means there is something wrong with the way your program is written. Some examples:

1. Misuse of commas when declaring a string:

var greeting = 'Hey there!"

When we run this code we'll get an error: unterminated string literal.

2. Leaving out a parenthesis:

print"Hey")

When we run this code we'll get errors such as error: consecutive statements on a line must be separated by ';' and error: expected expression.


The reference error:

A reference error occurs when the Swift compiler sees a word it does not recognize. Some examples:

1. Misspelling a class / function name:

prnt("Hey")

When we run this code we'll get an error: cannot find 'prnt' in scope.

2. Using a non-existent variable / Misspelling a variable's name:

let animal = "parrot"
print(aniimal)

When we run this code we'll get an error: cannot find 'aniimal' in scope.


Assignment
Follow the Coding Tutorial and let's practice with errors!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check