A variable is essentially a container that holds a piece of information. In Swift 3 these are not much changed from earlier versions of Swift.
But let’s go over them anyway 🙂
Can I change a variable?
There are 2 keywords we use to describe whether a variable can be changed or not:
Var implies ‘variable’ which means you can change it later on. Example:
var str = "Hello, playground"
str = "New data"
Let is not changeable later on. Example:
let str = "Hello, playground"
str = "New data" //BIG ERROR
Let STOPS people (including you) from messing up constants that shouldn’t be changed (or mutated to be grammatically correct)
A string holds a bunch of text, just like you might expect. In the above examples we declared strings ‘implicitly’. Ie, Xcode figured out that the variables enclosed in ” ” are strings (same in most other languages). But what if it’s not so obvious, or we want to ‘explicitly’ tell Xcode that we definitely want a string type? Example:
var str : String = "Hello, playground"
let str : String = "Hello, playground"
The great thing about this approach is that there is NO confusion about the variable type!
There are many types of numbers in all languages, primarily for reasons of efficiency I believe. The simplest is an integer (a whole number).
var myNum = 3
myNum = -1
myNum = 1200
Then we get the next 2 most common numbers: doubles and floats:
var myNum: Double = 7.2
var newNum: Float = 7.2
Clearly these can hold decimal values, but what’s the difference between them? Double can hold about twice as many digits compared to float (impressive, double, very impressive). If in doubt then double is preferred, Apple said so!
Sounds like an alien race doesn’t it? Well they’re much less exciting than that! A boolean holds a true or false value. Eg:
var myBool: Boolean = true
myBool = false
Insanely useful for keeping track of application states. Stuff like:
Is the oven on at home? (
var ovenOn = true
And when it’s switched off:
Is the oven on? (
var ovenOn = false
—-> No, the kitchen won’t burn down!
Well, those are the 3 basic variable types you’ll be using a lot of in Swift 3. There are many many more but once you know the basics (as outlined here) you should find them super easy to use.