Learn to Code via Tutorials on Repl.it!

← Back to all posts
A Crash Course on Swift
XanderEhlert (137)

Swift is a powerful and intuitive programming language for macOS, iOS, watchOS, tvOS and beyond.

  • Apple

It surprised me when I saw that no one had done a Swift crash course before, so I decided to make one. BTW I wrote this in like an hour so tell me if there are any typos.

Background

Swift was based on many different languages. Some of these include Python, Java, Rust, and more. Similar to Rust, Swift was made to have high usability and performance. Swift uses a compiler to run its code (similar to C/C++). Anyway, enough background, time to get started.


Getting Started

As tradition suggests, the first line of code should print Hello, World. In Swift, you accomplish this using similar syntax with Python 3.x
print("Hello, World!")
Although it is similar in syntax to python, you cannot use single quotes.

Declaring variables

Similar to C/C++ and some other languages, you have to declare variables before using them. This is done by using the var keyword.
e.g. var myVariable = 5
You can also specify the type of a variable using a colon. The types of variables are

  • Int - an integer such as 5 or -23
  • Float - a number with a decimal point such as 4.1 or 1.0 or -5.3
  • Double - a more accurate float
  • Bool - true or false
  • String - a collection of characters such as "Hello, People"
  • Character - a single letter or character such as "A"
    Note: Swift is very sensitive when it comes to capitals vs lowercase

Here's an example of declaring variable type
var myVariable: Int = 6

Declaring variables used later

This section will be short. To declare variables that you want to use later, but don't know the value of it yet, just declare the type.
e.g. var myVariable: Int

Another type of storage - Constants

Constants are variables that can't be changed. If you try to change it, the Swift compiler will get mad.

You declare constants using the keyword let
e.g. let myVariable = 5
Another note: you do not need to declare variable type- normally the compiler assumes it for you.

Do Maths

You might be asking yourself, but what if I wanted to add variables!

Doing math stuff in Swift is very similar to other languages:

  • + - add
  • - - subtract
  • * - multiply
  • / - divide
  • % - get remainder

e.g.

var x = 5
var y = 2
x = y + 4

Compound operators

Similar to other languages, if you wanted to add a number to a variable and make it equal to that same variable, you can shorten it using

+=
-=
*=
or /=

e.g.

var myVar = 5
myVar = myVar + 3

can be shortened using

var myVar = 5
myVar += 3

Printing variables

Let's say you were writing a code where it takes two numbers and then adds them. But how do you print them!

It's quite simple actually. Here's how you do it: print("Here is my variable! \(variableName)")
If you couldn't tell, you escape the variable using \(variableName)

You could also print the variable by itself.
e.g.

var myVar = 5
print(myVar)

Comments

Single line comments use //
e.g. // If this was in code, it wouldn't run!
Multi-line comments start with /* and end with */
eg.

/* 
none of this will run
ashdgfjhasdg
sadfhgsdajhfgkashjdgfkahjs
*/

If and Else statements

Let's say you wanted to print something based off if a variable is 3 or not. You would you an if/else statement which looks like:

if condition {
  // code to be run
} else {
  // code to be run if condition is false
}

**Remember to close and open with brackets.

Else If statements

You can also combine multiple if/else statements (similar to elif/eslif).
The syntax is:

if condition1 {
  // code
} else if condition2 {
  // more code
} else {
  // even more code
}

Comparison Operators

Comparison Operators are things that evaluate in if/else statements.
They include

< // less than
> // greater than
<= // less than or equal to
>= // greater than or equal to
== // equal to
!= // not equal to

e.g.

var myVar = 5
if myVar == 2 {
  print("It's two!")
} else if myVar > 6 {
  print("It's greater than 6!")
} else {
  print("IDK what it is")
}

Logic Operators

There are 3 main Logic Operators:

  • and - sees if both statements are true
  • or - sees if one or both statements are true
  • not - reverses the value from true to false and vice versa

In Swift, these are achieved by ! for not, && for and, and || for or.
e.g.

var t = true
var f = false
print(t || f) // prints true
print(t && f) // prints false
print(!t) // prints false

You can also combine these and use parenthenses for clarification.

Loops

Ranges

Ranges are created using the ... operator.
e.g. let myVar = 2...7

For-in loop

A For-In loop iterates over a collection of things.
e.g.

for char in "Hello, world!" {
  print(char)
}

Continue

Putting continue in a loop will make the loop skip to the next iteration.

Break

Break is similar to continue, except when you use break, the loop stops.

Underscore in For-in loops

If you never use the variable before the in in a for-in loop, you can use an underscore _ to signify it. If you don't, the compiler throws a warning at you.

While loop

Similar to a For-in loop, a while loop is also a loop. Except for a while loop keeps iterating until the provided condition is true
e.g.

var myCount = 1
let stop = 5

while counter < stop {
  print(counter)
  counter += 1
}

Getting User Input

Use readLine()! if you want to get a user input.
e.g.

var user = readLine()!
print(user)

Although the ! is not required, if you don't use it, the compiler will throw an error at you.

That's all I have for now.

Upvote for part 2!

Commentshotnewtop
theangryepicbanana (1629)

A few thoughts:

Similar to Rust, Swift was made to have high usability and performance (similar to Rust)

You mention "similar to Rust" twice here lol.

Similar to C/C++, you declare variables using the var keyword

C nor C++ use var for declaring variables, but languages like JavaScript and Dart do.

Although the ! is not required, if you don't use it, the compiler will throw an error at you.

Yes, this is because readLine returns an optional String type. If the user didn't enter anything or something weird happened during input, the value is nil (like None in python, however it is only allowed to be present in values with an optional type).

A few overall thoughts:

  • camelCase is the Swift naming standard rather than snake_case.
  • You probably could have gone over optional values and if let statements (since they are related) since it's not that complex to explain (?).
  • switch/case statements also could have been included, however it's understandable why they were because they can be kinda complex with pattern matching and stuff.
  • You could have mentioned exclusive ranges (>.. and ..<) in addition to normal ranges.

Other than that, this looks pretty solid. Good job!

XanderEhlert (137)

@theangryepicbanana thanks i changed the Rust thing and the phrasing for declaring variables

XanderEhlert (137)

@theangryepicbanana annnnnd i just changed it all to camelCase

DynamicSquid (3558)

Unrelated but...

Although it is similar in syntax to python, you cannot use single quotes.

This got me thinking, why does Python use single quotes? In every other language single quotes represent characters, but I guess Python doesn't have characters. But still! There's just something about single quotes that just looks... off

XanderEhlert (137)

@DynamicSquid in my opinion single quotes are easier to type maybe that's just me tho

DynamicSquid (3558)

@XanderEhlert I'm kind of used to pressing SHIFT lol

XanderEhlert (137)

@DynamicSquid well i only know swift and python but I barely use swift so..........

theangryepicbanana (1629)

@XanderEhlert @DynamicSquid single quotes can't be used for strings in Swift because they are used for characters instead (which are essentially single-character strings that act a bit more like an integer than a string)

xxpertHacker (388)

@DynamicSquid What about Bash? Just like JavaScript, there are 3 qquote types: backtick (`), single quote apostrophe ('), and double normal quote (").

DynamicSquid (3558)

@StudentFires three? oh wow, i didn't know that!

xxpertHacker (388)

@DynamicSquid JavaScript, Perl, and Bash do. I think using the backtick (grave accent mark) is a cool idea, since you never see a backtick. You can turn an entire document into a string by using them, since they are extremely rare.

xxpertHacker (388)

@DynamicSquid I like how my memoization post got 20 cycles (- my own), my whole book last night was unseen.

xxpertHacker (388)

@DynamicSquid It was an exaggeration on it's length. It's too damn long. I'll eventually repost it cut up into sections.

AmazingMech2418 (899)

@DynamicSquid JavaScript also uses single quotes. However, single quotes do denote the char data type in C++ and C as well as other languages. However, Python and JS don't have the char data type since their data types are implicit (also they don't even have a char data type, just string, similar to how they don't have int, just number).

AmazingMech2418 (899)

@StudentFires The backtick also doesn't break with new lines either, so you don't have to use "\n" and can just press enter.

xxpertHacker (388)

@AmazingMech2418 Backtick (accent mark) also allows embedded expressions, similar to Python.

`This is a ${typeof ``} data type!`
AmazingMech2418 (899)

@StudentFires In JS, it is

`some text ${embedded expression}`

However, python just uses

f"some text {expression}"

without backticks.

xxpertHacker (388)

@AmazingMech2418 By "similar to Python," I was solely referring to the idea of embedded expressions in a string.

DynamicSquid (3558)

@AmazingMech2418 Oh yeah, I forgot about those embedded expressions. I hate them...

AmazingMech2418 (899)

@DynamicSquid Why? I use them all the time in JS.

DynamicSquid (3558)

@AmazingMech2418 Noo... in C++ we separate different types, not combine them!

AmazingMech2418 (899)

@DynamicSquid Well, in C, there is the printf function which works similarly to the embedded expressions. I actually like it.

DynamicSquid (3558)

@AmazingMech2418 The only thing I like about C is it's casting. Everything else I hate. Whenever I see someone coding in C++ using C functions - traitor!