Swift - Programming Language
Recap of previous chapters: Swift basics (Data types, control statements, functions, class etc)
Swift is object-oriented programming language from Apple. Swift could be used to create a small
"hello world" application as well a completere operating system. It's powerful, modern and fast.
Swift is currently available to MacOSX and Linux platoforms. Apple has made Swift as an open-source code
compiler and Swift compiler's source code is available at github.
- let and var are the keywords which are written before and constant and variable data-types.
The value of a constant doesn't need to be known at compile time but it should be assigned exactly once.
let targetScore = 100
Swift is type safe language, so it does allow data of certain type to be converted or passed to another type.
var currentScore = 47
Swift also provide a feature called 'Type Inference', it means if the data-type is not given for a constant
or variable explicitly then Swift deduces the type from the value provided. As in above two examples targetScore and
currentScore has been inferred it's type as Int.
Swift provides if, if-else and switch statements to control the flow of code under certain conditions.
if statement doesn't accept any value other than Bool and also brackets like () are not required while curly braces are must.
In switch the cases doesn't continue to next case block by default and also swift allows complex case matching statements than simple integer.
Also default case is mandatory.
If some variable's value is not certainly known, then it could have an optional value as nil. The value nil
does not mean a NULL address rather it means there is no value and it is used similarly for all data type.
Question mark (?) is added against a variable declaration to mark it a optional value.
let targetScore: Int? = nil
In the above example the value is unknown when game begins.
var currentScore: Int? = nil
Double question mark (??) operator is used to provide a default value to an optional value.
Swift provide four basic types of loop statements: for, for-in, while, repeat-while.
- Example of a swift function as given below:
func add(let a: Int32, let b: Int32) -> Int32