Intro To Swift 3

Published: October 16, 2016

Time to read: 7 min

Intro To Swift 3

Published: October 16, 2016

Time to read: 7 min

It’s Here!

So you’ve been wanting to get into iOS development? Well, now’s the best time to get in. With the introduction of Swift, creating iPhone, Apple Watch, and MacOS apps has never been easier. In this tutorial, I will go over the Swift language that you will need to jump right into iOS development. Though I won’t be going over Coco Touch, if you can gain a good grasp of the Swift language, it will come with ease and a bit of practice.

Requirement

Xcode version 8

A basic understanding of programming.

Now for creating actual iOS and Mac OS apps, you will need a Mac and Xcode to actually program, for this tutorial you can use programiz’s Swift repl.

So rev up your Xcode V8 or open up programiz’s awesome swift repl and let’s get started.

Getting Started

Like in the great tradition of computers, let’s kick off by typing our very first non-impressive Swift program, Hello World!

code block is swift
print("Hello World!)

As you can see, Swift is a modern language with easy-to-read syntax. If you’ve ever programmed in Javascript, ES 2015, then Swift will come a bit easier in my opinion. Swift is getting more popular by the day. People have even stretched the limits of the language and set up websites, back-end servers, and even ran Android apps built with Swift. Many are even calling it, if they dare, the future of the web. If you poke your ear on the interwebs, you will hear chitter and theories of how Swift will one day replace Javascript in the far future.

Storing Values

In order to store data in Swift we have two options: variables and constants. Both are similar but have different uses. But are used to store data such as String, Int, Booleans, Float, and even other variables and constants. The main difference is Variables are used to store data that can be later changed, and Constants hold data that can never be modified.

code block is swift
var playerScore: 0

let playerName: String

To store our player score, we use the ‘var’ keyword for variable then our variable name and the assign operator ‘=‘ and assign it to 0

For our player name, we use the ‘let’ keyword for constant and this time we could assign our variable to a data type( String, Int, etc) for later use. In this case our player name is String. If you would like, feel free to change it to whatever you like, i.e.

code block is swift
let playerName = "Jon Snow"

Are a few more examples of variables and constants

code block is swift
var king: String
var starksAlive: Int
let nightWatchOath = "Night gathers, and now my watch begins"
let favoriteCharacters = 3
var JonFather = false

print("As the \(nightWatchOath)") // As the Night gathers, and now my watch begins

Creating Arrays

Another way Swift is a bit similar to Javascript is in its creation of arrays. We start with either var or let our array name and open and closing bracket. Also, in case you didn’t know, in programming, we count from 0 up, so miami would not be 1 but 0, paris 1, and nyc 3

code block is swift
var cities = [
    "miami",
    "paris",
    "nyc"
]

And now say we wanted to print the stored values, we have multiple ways

code block is swift
print(cities) // ["miami", "paris", “nyc"]

or

code block is swift
print(cities[0]) // miami

We can also change our values like so, this changes our value from “nyc” to “new york”.

code block is swift
cities[2] = "new york"

We can also have key and value or dictionary with arrays.

code block is swift
var top3foods = [
    "Pizza": "1st",
    "Burgers": "2nd",
    "Fried Chicken": "3rd"
]

Now another cool feature is getting the index our items in our array with a new method index. Let’s reuse our cities array and we want to know the index or position of ‘paris

array.index(of:"paris")

And if we check in our playground we would get our index at 1.

Adding Some Logic

Now to the good part, adding some logic to our code. With Swift 3, Apple had decided to really distance itself from the C language, from which Objective-C and easier Swift was based on. Let’s get started with good ol’ For loop.

Before, you might have seen a for loop for

code block is swift
(i =1; i < 10; i++) {
    console.log(i)
}
//1
//2
//3 .. etc etc

While the concept is still true with swift, the syntax has changed just a bit. Take a look.

code block is swift
for i in 1..<10 {
    print(i)
}

As you can see, it’s still just as simple as ever, though it can take some getting used to. If anything, it should be easier to articulate, as if we’re spreading in real person. For i in 1 to 10 print i.

Let’s take a look at another example with For loop and If Else statements

code block is swift

let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0

for score in individualScores {
    if score > 50 {
        teamScore += 3
    } else {
        teamScore += 1
    }
}

print(teamScore) // 11

So let’s check out what we have here: we have an array individualScores, a variable teamScore that is 0. Then our For Loop, score you can imagine it as i = 1 in a usual For Loop, score is a new variable within the scope of the For Loop.

Putting The Fun Back in Functions!

Now that we got our string, our values and data, let’s move on how to set up functions.

First we start with the func keyword for function, then a pair of parentheses and opening and curly braces, a lot like Javascript. In case this is new to you, functions are instructions we program on how to modify and change our data or value.

code block is swift
func sayMyName() {
    print("Heisenberg")
}

So here we have a function that prints out the string “Heisenberg”. Now to see the bad boy in action, we have to activate or call the function, we have to call the function name and followed by parenthesis.

sayMyName()

code block is swift
Heisenberg

We can also make our functions more personal by adding parameters for arguments. Take a look at the example below:

code block is swift
func startGameOfThrones(playerName: String) {
    print("Hello \(playerName)")
}

So we created a function called startGameOfThrones and has an parameter of Name which is of type String. Then within our curly braces when have our print method that includes the ( ) of adding our parameters directly in our statement.

code block is undefined
startGameOfThrones(playerName: "Jon Snow")

Here is another example of functions, but this time we are returning a value

code block is swift
func add(x:Int, y:Int) -> Int {
    return x+y
}

add(x: 2, y: 1) // 3
add(x: 8, y: 3) // 11

To return a value, after our parameters, we had to add the -> symbol and the returning data type, so this could be either a String, Int, Boolean, Float, and even our customer objects. After we have to add the return keyword.

Conclusion

So we covered how to store data in two different ways with variables and constants. We took a look at how to create and modify arrays, how to add logic and how to create functions. We have barely scratched the surface. Swift 3 is a great language to learn – it’s simple, clean and safe. I highly recommend you download the offical Swift 3 handbook by Apple “The Swift Programming Language 3rd Edition”. As well check out some of Apple’s great documentation and the official website for Swift.

Till next time and happy coding.