Fundamentals of Swift Example Tutorial

In this tutorial we’ll look into the basic syntax of Swift and run it in our console.

Overview

Click Get started with a playground. A playground is a new type of file that allows us to test out Swift code, experiment and play around with it and see the results of each line in the sidebar.

Variables and Constants

  1. Variables are declared using the keyboard var that stands for variable
  2. Specifying the type of variable is optional. Swift compiler has a feature called Inferred Typing to automatically predict the type of variable by the value assigned. Both of the below statements are equivalent. (Not ending with a semi-colon doesn’t make any difference too.)
    var a="Hi";
    var a:String="Hi"
  • To define a constant the declaration must start with a let keyword. Assigning a different value to the same variable will give rise to compile time error
  • The types that can be assigned to variables are- Int, Float, Double, Bool, String

Conditional Statements and String Interpolation

In swift there is no need to put parentheses in the if-else conditions. This leads to better readability.
A String Interpolation is a simple way of combining variables and constants inside a string.

print("This is the first Swift Tutorial. "+"(a)")

The above snippet prints out the string to the console. It contains a string variable appended to the string as it’s seen above.

An example using the if-else with String interpolation is given below.


var i=1;
let j=2;
if i<j {
print("If statement is executed i and j are "+"(i) "+"(j)")
}
else{
print("Else statement is executed i and j are "+"(i) "+"(j)")
}

Arrays and For loops

  1. Arrays are defined as follows (type is specified either implicit or explicit :
    let numbersArray = [1, 2, 3]
    var stringArray:[String] = ["Jan", "Feb", "March"]
    
  2. To retrieve the value at a given index we use the form similar to that in C :
    stringArray[index_number]
  3. The second array is mutable new elements can be added in it. the append method is used to add a new element in it. The following snippet demonstrates the same.
    stringArray.append("April")
  4. To append a new element at a specific index instead of at the end, the insert method is used as shown below.
    stringArray.insert("Dec", atIndex: 1) 
  5. To assign different values to a range of indexes of an array we use the following syntax.
    stringArray[1..<3] = ["2","3","4"]

    The above statement implies, inclusive of the startIndex and exclusive of the endIndex

  6. To merge two arrays into one. We use the + operator
    var both = stringArray + stringArray

For loop in a Swift is similar to that in Objective-C except the fact that no parentheses are needed. The more recommended approach is the fast enumeration one. It’s given below.


for s in stringArray {
    print("String is "+"(s)")
}

The classic old approach is to iterate over the elements using the count static method over the array. It’s given below.


for i in 0..<stringArray.count {
    let p = stringArray[i]
    print("String is "+"(p)")
}

The < operator is a non-inclusive range operator and doesn’t include the upper bound value.

Dictionaries

Dictionaries are another collection type that go a step ahead from Arrays in the fact that they let us access values based on the specific keys we specify. They are useful when we need to access an element from a value other than the standard identifier. The code snippet below shows how it’s declared and how the elements are accessed.

var person = ["month": "April", "language": "Swift", "website": "journaldev.com"]
person["language"]

Note: If the key entered doesn’t exist. Then a nil would be returned. Try it out.

Explicitly specifying the type is done like this:


var dict2: Dictionary<Int, String> = [1:"1",2:"2"]

Switch Statements

A switch condition loop is a bit different in Swift than what we’ve seen till now.

  1. A break statement is not needed. On the contrary if we want to go to the next case we use a fallthrough keyword.
  2. A single case can check for more than one values by specifying the range in the case. An example is given below.
    
    let x=5
    switch x {
    case 0...1:
        print("This is printed for the range 0 to 1 inclusive")
    case 2...4:
        print("This is printed for the range 2 to 4 inclusive")
    case 5...8:
        print("This is printed for the range 5 to 8 inclusive")
        fallthrough
    default:
        print("Default is only needed when cases are not exhaustive. Else compile time error will come.")
    }
    

    In the above code, fallthrough would print the next statements as well

  3. The default statement isn’t needed if the cases cover all the possibilities. But if there is a case not covered then the default statement is a must, else compile time error would occur.

Functions

Functions are reusable pieces of codes that can be invoked and run anywhere once defined. They begin with the letter func.

A basic example of a user defined function is given below.


func firstFunction() {
    print("A basic function")
}

The above statement will only be executed when the firstFunction() is called.

The syntax when a function has a return type is given below along with an example.


func thisReturns(name: String) -> Bool {
    if name == "JournalDev" { return true }
    return false
}
if thisReturns("JournalDev") {
    print("True is returned")
}

Swift gives us the liberty to make a return type optional by appending a “?” at the end of it.

func thisReturns(name: String) -> Bool" {}

Enumerations

Swift is one language that has made enums powerful than before. We can define our own data types using enums and pass them in functions. An example is given below.


enum MoodType {
    case Happy, Sad, Worried, Tensed, Angry
}
func getMood(mood: MoodType) -> String? {
    if mood == MoodType.Happy {
        return nil
    } else {
        return "Something is wrong with your mood today!"
    }
}
getMood(.Sad)

We’ve defined a MoodType enum that’s passed as a parameter in the function.

  • Note: MoodType.Happy is same as .Happy since Swift uses type inferencing to detect the type of the data. This is evident in the code when we’ve called that function.

A quick look at our playground with almost all the above code snippets compactly placed is given below.

ios-swift-basics-playground

In this tutorial we’ve covered the basic Swift syntax with examples. We’ll cover the more complex stuff in the iOS Tutorials.

By admin

Leave a Reply

%d bloggers like this: