Basic Of Swift Programming
Write your code in a file named hello.swift:
print(“Hello, world!”)
To compile and run a script in one step, use swift from the terminal (in a directory where this file is located):
To launch a terminal, press CTRL + ALT + T on Linux, or find it in Launchpad on macOS. To change directory, enter cddirectory_name (or cd .. to go back)
$ swift hello.swift Hello, world!
A compiler is a computer program (or a set of programs) that transforms source code written in a programming language (the source language) into another computer language (the target language), with the latter often having a binary form known as object code. (Wikipedia)
To compile and run separately, use swiftc:
$ swiftc hello.swift
This will compile your code into hello file. To run it, enter ./, followed by a filename.
$ ./hello
Hello, world!
Or use the swift REPL (Read-Eval-Print-Loop), by typing swift from the command line, then entering your code in the interpreter:
Let’s break this large code into pieces:
- func greet(name: String, surname: String) { // function body } — create a function that takes a name and a surname
- print(“Greetings \(name) \(surname)”) — This prints out to the console “Greetings “, then name, then surname. Basically \(variable_name) prints out that variable’s value.
- let myName = “Homer” and let mySurname = “Simpson” — create constants (variables which value you can’t change) using let with names: myName, mySurname and values: “Homer”, “Simpson” respectively
- greet(name: myName, surname: mySurname) — calls a function that we created earlier supplying the values of constants myName, mySurname.
Running it using REPL:
Press CTRL + D to quit from REPL.
Your first program in Swift on a Mac
Download XCode from AppStore
After the installation is complete, open Xcode and select Get started with a Playground:
On the next panel, you can give your Playground a name or you can leave it MyPlayground and press Next:
Select a location where to save the Playground and press Create:
The Playground will open and your screen should look something like this:
Now that the Playground is on the screen, press ⇧ + cmd + Y to show the Debug Area.
Finally delete the text inside Playground and type:
print(“Hello world”)
You should see ‘Hello world’ in the Debug Area and “Hello world\n” in the right Sidebar:
Congratulations! You’ve created your first program in Swift!
Installing Swift
First, download the compiler and components.
Next, add Swift to your path. On macOS, the default location for the downloadable toolchain is /Library/Developer/Toolchains. Run the following command in Terminal:
export PATH=/Library/Developer/Toolchains/swift-latest.xctoolchain/usr/bin:”${PATH}”
On Linux, you will need to install clang:
$ sudo apt-get install clang
If you installed the Swift toolchain to a directory other than the system root, you will need to run the following command, using the actual path of your Swift installation:
$ export PATH=/path/to/Swift/usr/bin:”${PATH}”
You can verify you have the current version of Swift by running this command:
$ swift — version
Optional Value and Optional enum
Optionals type, which handles the absence of a value. Optionals say either “there is a value, and it equals x” or “there isn’t a value at all”.
An Optional is a type on its own, actually one of Swift’s new super-powered enums. It has two possible values, None and Some(T), where T is an associated value of the correct data type available in Swift.
Let’s have a look at this piece of code for example:
In fact if you add a print(x.dynamicType) statement in the code above you’ll see this in the console:
Optional<String>
String? is actually syntactic sugar for Optional, and Optional is a type in its own right.
Here’s a simplified version of the header of Optional, which you can see by command-clicking on the word Optional in your code from Xcode:
Optional is actually an enum, defined in relation to a generic type Wrapped. It has two cases: .none to represent the absence of a value, and .some to represent the presence of a value, which is stored as its associated value of type Wrapped.
Let me go through it again: String? is not a String but an Optional.The fact that Optional is a type means that it has its own methods, for example map and flatMap.
Variables & Properties
Creating a Variable
Declare a new variable with var, followed by a name, type, and value:
var num: Int = 10
Variables can have their values changed:
num = 20 // num now equals 20
Unless they’re defined with let:
let num: Int = 10 // num cannot change
Swift infers the type of variable, so you don’t always have to declare variable type:
Variable names aren’t restricted to letters and numbers — they can also contain most other unicode characters, although there are some restrictions
Constant and variable names cannot contain whitespace characters, mathematical symbols, arrows, private-use (or invalid) Unicode code points, or line- and box-drawing characters. Nor can they begin with a number
Source developer.apple.com
Property Observer
Property observers respond to changes to a property’s value
willSet is called before myProperty is set. The new value is available as newValue, and the old value is still available as myPropert
didSet is called after myProperty is set. The old value is available as oldValue, and the new value is now available as myProperty .
Note: didSet and willSet will not be called in the following cases:
Assigning an initial value Modifying the variable within its own didSet or willSet
The parameter names for oldValue and newValue of didSet and willSet can also be declared to increase readability:
Lazy Stored Properties
Lazy stored properties have values that are not calculated until first accessed. This is useful for memory saving when the variable’s calculation is computationally expensive. You declare a lazy property with lazy:
lazy var veryExpensiveVariable = expensiveMethod()
Often it is assigned to a return value of a closure:
Lazy stored properties must be declared with var.
Property Basics
Properties can be added to a class or struct (technically enums too, see “Computed Properties” example). These add values that associate with instances of classes/structs:
In the above case, instances of Dog have a property named name of type String. The property can be accessed and modified on instances of Dog:
These types of properties are considered stored properties, as they store something on an object and affect its memory.
Computed Properties
Different from stored properties, computed properties are built with a getter and a setter, performing necessary code when accessed and set. Computed properties must define a type:
A read-only computed property is still declared with a var:
Read-only computed properties can be shortened to exclude get:
Local and Global Variables
Local variables are defined within a function, method, or closure:
Global variables are defined outside of a function, method, or closure, and are not defined within a type (think outside of all brackets). They can be used anywhere:
Global variables are defined lazily (see “Lazy Properties” example).
Type Properties
Type properties are properties on the type itself, not on the instance. They can be both stored or computed properties. You declare a type property with static:
In a class, you can use the class keyword instead of static to make it overridable. However, you can only apply this on computed properties:
This is used often with the singleton pattern.
In our next article, we will examine the types of values in the swift programming language with you. See you…