swift fundamentals

Swift fundamentals

In this tutorial, we’ll look into the basic syntax of swift and run it in our console. 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

  • Variables are declared using the keyboard var that stands for variable
  • Specifying the type of variable is optional.
  • The swift compiler has a feature called Inferred Typing to automatically predict the type of the 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 aString = "BaluTutorial.com"

var bString: String = "BaluTutorial.com"
  • To define a constant the declaration must start with a let keyword.
  • Assigning a different value to the same variable will give rise to a compile-time error
  • The types that can be assigned to variables are- Int, Float, Double, Bool, String
let intValue = 12

intValue = 40   //Error : Cannot assign to value: 'intValue' is a 'let' constant

intValue = 34.70  //Error: Cannot assign to value: 'intValue' is a 'let' constant

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.

let aValue = 1
print("This is the swift foundation tutorial. "+"\(aValue)")

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 aValue = 1
let bValue = 2

if aValue < bValue {
    print("If statement is executed i and j are "+"\(aValue) "+"\(bValue)")
} else {
    print("Else statement is executed i and j are "+"\(aValue) "+"\(bValue)")
}

Arrays and For loops

  • Arrays are defined as follows (type is specified either implicit or explicit
let numbersArray = [10, 20, 30]
var stringArray:[String] = ["Jan", "Feb", "March"]
  • To retrieve the value at a given index we use the form similar to that in C language
    stringArray[index_number]
  • 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")
  • 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)
  • To assign different values to a range of indexes of an array we use the following syntax.
stringArray[1..<3] = ["20","30","40"]
  • The above statement implies, inclusive of the startIndex and exclusive of the endIndex
  • To merge two arrays into one. We use the + operatorvar
let bothArray = stringArray + stringArray
  • For loop in a Swift is similar to that in Objective-C except for the fact that no parentheses are needed.
  • The more recommended approach is the fast enumeration one. It’s given below.
import Foundation

var stringArray:[String] = ["Jan", "Feb", "March"]
stringArray.append("April")

for item in stringArray {
    print("String is "+"\(item)")
}
  • The classic old approach is to iterate over the elements using the count static method over the array. It’s given below.
import Foundation

var stringArray:[String] = ["Jan", "Feb", "March"]
stringArray.append("April")

for i in 0..<stringArray.count {
    let item = stringArray[i]
    print("String is "+"\(item)")
}
  • The < operator is a non-inclusive range operator and doesn’t include the upper bound value.

Dictionaries

Dictionaries are another collection type that goes 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.

import Foundation

var person = ["month": "June",
              "language": "Swift",
              "website": "valututorial.com"]

person["language"]  // prints "Swift" on console
If the key entered doesn’t exist. Then nil would be returned.
  • Explicitly specifying the type is done like this
import Foundation

var dictionary: Dictionary<Int, String> = [1:"10",
                                           2:"20",
                                           3:"30"]

dictionary[2]

dictionary[4]   // return nil beacuse key 4 not exest

dictionary["key"]  //Error: Cannot subscript a value of type 'Dictionary<Int, String>' with an index of type 'String'

Switch Statements

  • A switch condition loop is a bit different in Swift than what we’ve seen till now.
  • A break statement is not needed. On the contrary, if we want to go to the next case we use a fallthrough keyword.
  • A single case can check for more than one value by specifying the range in the case. An example is given below.
import Foundation

let xValue = 5
switch xValue {
    case 0...1:
        print("This is printed for the range 0 to 1")
    case 2...4:
        print("This is printed for the range 2 to 4")
    case 5...8:
        print("This is printed for the range 5 to 8")
        fallthrough
    default:
        print("Default is only needed when cases are not exhaustiv")
}
  • 

In the above code, fallthrough would print the next statements as well
  • 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 code 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 myFunction() {
    print("This is a function")
}
  • The above statement will only be executed when the myFunction() is called.
  • The syntax when a function has a return type is given below along with an example.
import Foundation

func thisReturns(name: String) -> Bool {
    if name == "BaluTutorial" {
        
        return true
    }
    
    return false
}

if thisReturns(name: "BaluTutorial") {
    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.

import Foundation

enum MyMoodType {
    case Happy
    case Sad
    case Worried
    case Tensed
    case Angry
}

func getMyMood(mood: MyMoodType) -> String? {
    if mood == MyMoodType.Happy {
        
        return nil
    } else {
        
        return "Something is wrong with your mood today!"
    }
}

getMyMood(mood: .Sad)

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

whatsapp

error: Content is protected !!