String and Characters

string is a series of characters, such as "hello, world" or "albatross". Swift strings are represented by the String type. The contents of a String can be accessed in various ways, including as a collection of Character values.

String Literals

You can include predefined String values within your code as string literals. A string literal is a fixed sequence of textual characters surrounded by a pair of double quotes ("").

Use a string literal as an initial value for a constant or variable:

 let a=”Hello”
 swift automatically infer the type of variable a and assign it with type of literal “Hello”
empty string is created like this..
       var emptyString = “”
      or var x=String()
if you want to check that string is empty then there is a method isEmpty. Have look on following code
      var a=String()
      var b=”Helllo”
      if a.isEmpty {
                       print(“String is empty”)
                            } 
     if b.isEmpty {
     print(“String is not empty”)
                          }

Control Structure

Swift provides all the familiar control flow statements from C-like languages. These include for, for-in,  while, if,  guard,  switch, break and continue.

For loops

There are two types of for loop in swift first one is  for-in  and second is  simple for loop.

  1. The forin loop performs a set of statements for each item in a sequence.

  2. The for loop performs a set of statements until a specific condition is met, typically by incrementing a counter each time the loop ends.

The simple format for for-in is as follows

for anyVariable in 1range {
print(“the value in anyvariable is \(anyvariable)”)
}

The value of anyVariable  in for-in is constant and it takes the value in between 1 to the range inclusive.

simple for loop is same as it is written in C.

for  var i=0; i<10; i++ {
print(“hello”)
}

If you don’t need the value of variable in for loop you can ignore it writing like this

for _ in 110 {
print(“hello friends”)
}

The screenshot of these three for loop is given below.

Screen Shot 2016-02-21 at 8.42.53 PM
Image: ScreenShots

for-in can be used to iterate on elements of dictionary for example.

var animals=[“Cow”: 8, “human” : 2, “ant”: 6 ]
 for (name, nooflegs) in animals{
print(“Animal \(name) has \(nooflegs) legs”)
}

Note : In for-in loop, if you iterating on dictionary the output order may be different. It is because dictionary is inherently unordered.

 

The illustration of for loop for all types discussed above can be downloaded here

While loop

while loop performs a set of statements until a condition becomes false. There are two types of while loop.

  1. while evaluates its condition at the start of each pass through the loop.

  2. repeatwhile evaluates its condition at the end of each pass through the loop.

while condition {
statements
}

While loop test the condition if condition is true the statements written get executed. This process keeps on going till the condition gets false.

repeat {

statements

} while Condition

repeat-while is used at the place of do-while in C programming.

Screen Shot 2016-02-22 at 4.22.13 PM

While loop program

While loop example can be downloaded from here

Condition Statements

There are two way for branching : if and switch. if is used to branch based on simple condition whereas switch is used for more complex conditions. if condition structure is as follows

if condition {

Statements

}

if-else structure:

if condition {

statements

} else if condition {

statements

} else {

statements

}

An Example:

var a = 72
if a <= 32 {
print(“It’s cool”)
} else if a >= 86 {
print(“It’s really hot”)
}

Switch

switch statement considers a value and compares it against several possible matching patterns. It then executes an appropriate block of code, based on the first pattern that matches successfully. A switch statement provides an alternative to the if statement for responding to multiple potential states.

In its simplest form, a switch statement compares a value against one or more values of the same type:

There are some specific properties related to switch :

  1. Every switch statement consists of multiple possible cases, each of which begins with the case keyword
  2. The body of each switch case is a separate branch of code execution.
  3. Every switch statement must be exhaustive. That is, every possible value of the type being considered must be matched by one of the switch cases
  4. If no case matches write in default case.

let anotherCharacter: Character = “w”
switch anotherCharacter {
case “a”,”b”,”c”:
print(“hello”)
case “A”:
print(“The letter A”)
default:
print(“Not the letter A”)
}

No Implicit Fallthrough

In contrast with switch statements in C and Objective-C, switch statements in Swift do not fall through the bottom of each case and into the next one by default. Instead, the entire switch statement finishes its execution as soon as the first matching switch case is completed, without requiring an explicit breakstatement. This makes the switch statement safer and easier to use than in C, and avoids executing more than one switch case by mistake.

The body of each case must contain at least one executable statement. It is not valid to write the following code, because the first case is empty:

 

let anotherCharacter: Character = “w”
switch anotherCharacter {
case “a”:
case “A”:
print(“The letter A”)
default:
print(“Not the letter A”)
}

Note: Multiple matches for a single switch case can be separated by commas, and can be written over multiple lines if the list is long:

Interval Matching

Values in switch cases can be checked for their inclusion in an interval. This example uses number intervals to provide a natural-language count for numbers of any size: for example:

Screen Shot 2016-02-23 at 6.53.04 AM

In the above example, anotherNumber is evaluated in a switch statement. Each case compares that value to a number or interval. It falls in range of 5..<10, therefore output is helooo3.

Brief description :

  1. The continue statement tells a loop to stop what it is doing and start again at the beginning of the next iteration through the loop.
  2. The break statement ends execution of an entire control flow statement immediately. The break statement can be used inside a switch statement or loop statement when you want to terminate the execution of the switchor loop statement earlier than would otherwise be the case.
  3. When used inside a loop statement, break ends the loop’s execution immediately, and transfers control to the first line of code after the loop’s closing brace (}).
  4. When used inside a switch statement, break causes the switch statement to end its execution immediately, and to transfer control to the first line of code after the switch statement’s closing brace (}).

Example for continue:

Screen Shot 2016-02-24 at 6.29.26 AM

Code for the same is here

Break

The break statement ends execution of an entire control flow statement immediately. The break statement can be used inside a switch statement or loop statement when you want to terminate the execution of the switchor loop statement earlier than would otherwise be the case.

  1. When used inside a loop statement, break ends the loop’s execution immediately, and transfers control to the first line of code after the loop’s closing brace (}).
  2. When used inside a switch statement, break causes the switch statement to end its execution immediately, and to transfer control to the first line of code after the switch statement’s closing brace (}).
  3. If you want to ignore a particular case in switch, use break as you can’t leave a case without statement. Therefore, break is the option to use

Screen Shot 2016-02-24 at 7.03.53 AM

The illustration of break is given in the screenshot above.

Example of break can be downloaded from here

fallthrough

Switch statements in Swift do not fall through the bottom of each case and into the next one. Instead, the entire switch statement completes its execution as soon as the first matching case is completed. By contrast, C requires you to insert an explicit break statement at the end of every switch case to prevent fallthrough. Avoiding default fallthrough means that Swift switch statements are much more concise and predictable than their counterparts in C, and thus they avoid executing multiple switch cases by mistake.

If you need c-Style fallthrough behaviour, it can be achieved by writing the keyword fallthrough in case you want that control is to fall to next case. For example have look into the screenshot below.

.Screen Shot 2016-02-24 at 7.17.17 AM

Introduction to swift

Swift is a new programming language for iOS, OS X, and watchOS app development. If you are already familiar with the objective C or C then it would be easy to understand the basic.

Swift provides the following properties


  1. Its own versions of all fundamental C and Objective-C such as Int for integers, Double and Float for floating point values, Bool for Boolean values and String for textual data.
  2. Three primary collection types – Array, Set and Dictionary
  3. Swift uses variables to store and refer to values by an identifying name.
  4. Swift also makes extensive use of variables whose values cannot be changed.
  5. introduction of advanced types not found in Objective-C, such as tuples. Tuples enable you to create and pass around groupings of values. You can use a tuple to return multiple values from a function as a single compound value.
  6. It is a type-safe language, which means the language helps you to be clear about the types of values your code can work with. If part of your code expects a String, type safety prevents you from passing it an Int by mistake. Likewise, type safety prevents you from accidentally passing an optional String to a piece of code that expects a nonoptional String.

Constants and Variables

Constants and variables associate a name with a value of a particular type. The value of a constant cannot be changed once it is set, whereas a variable can be set to a different value in the future.

Declaring Constants and Variables

Constants and variables must be declared before they are used. You declare constants with the let keyword and variables with the var keyword. Here’s an example.

  1. let a = 50
  2. var b = 1

This code is read as a is constant and holds 50 and b is a variable and holds 10. The value of a can’t be changed whereas b can have different value later on. The type of b is integer, it is inferred from the type of value assigned in it. Since, 10 is integer so the type of b is integer.

Type Annotations

You can provide a type annotation when you declare a constant or variable, to be clear about the kind of values the constant or variable can store. Write a type annotation by placing a colon after the constant or variable name, followed by a space, followed by the name of the type to use. For example

var myNameIs: String

The colon in the declaration represents “…of type…,”.  The code is read as myNameIs of type String.

Now myNameIs variable can store and String type like
myNameIs=”anil”

myNameIs=”AKG”

You can define multiple related variables of the same type on a single line, separated by commas, with a single type annotation after the final variable name:

var x, y, z: Int

Note

it is rare that you give the type annotations to variables in swift. Generally, type is inferred from the value assigned in.  You can have details of the same at Type Safety and Type Inference.

How to Print Variable, Constants

You can print the current value of a constant or variable with the print(_:separator:terminator:) function:

for example
var name=”AKG”
let anynumber=20
print(name)                       output :   AKG
print(anynumber)            output:    20

print(_:separator:terminator:) function has three arguments, the variable or constant you want to print, separator and terminator. Last two are optional. if you write this statement

print(“Hello, World!”)

it means you have passed one argument to print and it prints Hello world! with new line on Xcode’s  console pane. If you run the following line of code in Xcode

print(“Red”, “Blue”, “White”,”Black”, separator: “,”, terminator: “\n”)

The output would be

Red,Blue,White,Black

This is because separator is ‘,’ and terminator is new line. The default value of terminator is new line. If you rewrite the same code in this way and run

print(“Red”, “Blue”, “White”,”Black”, separator: “\n”)

The output would be as follows

Red
Blue
White
Black

This happens because the separator between two values is new line.

Swift uses string interpolation to include the name of a constant or variable as a placeholder in a longer string, and to prompt Swift to replace it with the current value of that constant or variable. Wrap the name in parentheses and escape it with a backslash before the opening parenthesis:

For instance

var x=20
print(“The number i am going to print is \(x). “)

The output would be

The number i am going to print is 20.

Another example is

var age=30
var name=”anil”
print(“Hello friends my name is \(name) and my age is \(age). “)

In this example, output is

Hello friends my name is nail and my age is 30.

Comments

You can put single line comment using // and multiple lines of comment using /* hello */.

For instance
// This is a comment
/* This is multiple lines of comments
example */

No Semicolons

You need not to put semicolon at the end of each statement. Swift has property, if new line is there at the end of statement it consider end of the statement. But if you wish to write multiple statements in a line you need to put semicolon to separate the statements.

For example

var x=100       // I have not put semicolon at the end of statement it is fine.

var y=20; var z=40; var s=50       // This is an example of having
// semicolons in a line.

All the above concept is implemented in swift on Xcode and available on my GitHub account. The link is here 

Integers and Floating-Point Numbers

Integers are whole numbers with no fractional component. It is either signed or unsigned. For example -10, 30 are signed and unsigned respectively . Swift provides signed and unsigned integers in 8, 16, 32, and 64 bit forms. These integers follow a naming convention similar to C, in that an 8-bit unsigned integer is of type UInt8, and a 32-bit signed integer is of type Int32. Like all types in Swift, these integer types have capitalized names.

Integer has its bounds (Minimum and Maximum). The min and max properties are used to find the minimum and maximum. For instance:

let theMinSizeOfIntegerIs= Uint8.min   // theMinSizeOfIntegerIs=0
let theMaxSizeOfIntegerIs= Uint8.max //theMaxSizeOfIntegerIs=255

In most cases, you don’t need to pick a specific size of integer to use in your code. Swift provides an additional integer type, Int, which has the same size as the current platform’s native word size:

  • On a 32-bit platform, Int is the same size as Int32.

  • On a 64-bit platform, Int is the same size as Int64.

Unless you need to work with a specific size of integer, always use Int for integer values in your code.

Like Int, swift provides UInt for unsigned integer.

Floating-point numbers are numbers with a fractional component, such as 4.23450.13, and -2723.15.

Swift provides two signed floating-point number types:

  • Double represents a 64-bit floating-point number.

  • Float represents a 32-bit floating-point number

 Note: Double has a precision of at least 15 decimal digits, whereas the precision of Float can be as little as 6 decimal digits

Type Safety and Type Inference

Swift is a type-safe language. A type safe language encourages you to be clear about the types of values your code can work with. If part of your code expects a String, you can’t pass it an Int by mistake.

Because Swift is type safe, it performs type checks when compiling your code and flags any mismatched types as errors. This enables you to catch and fix errors as early as possible in the development process.

If you write like this

let k=20

Here, type of k is not mentioned but swift has property to infer the type of k (any constant or variable) using the type of literal. Therefore, type of k is Int.

If you write like this

let z=3.456

In this case, type of z is double because swift always infer double when floating point literal is assigned.

Note 
  1. If you combine integer and floating-point literals in an expression, a type of Double will be inferred from the context

     let Pi = 3 + 0.14159 

     //Pi is also inferred to be of type Double

2. A literal value is a value that appears directly in your source code, such as 12 and 3.4

Numeric Literals

Integer literals can be written as:

  • decimal number, with no prefix

  • binary number, with a 0b prefix

  • An octal number, with a 0o prefix

  • hexadecimal number, with a 0x prefix

All of these integer literals have a decimal value of 17:

  1. let decimalInteger = 17
  2.  let binaryInteger = 0b10001 // 17 in binary notation
  3. let octalInteger = 0o21 // 17 in octal notation
  4. let hexadecimalInteger = 0x11 // 17 in hexadecimal notation

Floating-point literals can be decimal (with no prefix), or hexadecimal (with a 0x prefix).

Numeric Type Conversion

When arithmetic operation are performed on constant and variable, it requires that their types must be same. For instance

var i=20
var k=3.24
var p=i + k    // It produces an error because type of i and k are Int and Double respectively.

Therefore, to perform the above operation it needs to make it like this

var p=Double(i) + k  // It works

Note

The rules for combining numeric constants and variables are different from the rules for numeric literals. The literal value 3 can be added directly to the literal value 0.14159, because number literals do not have an explicit type in and of themselves. Their type is inferred only at the point that they are evaluated by the compiler.

 The detailed illustration of Integer and Floating-Point numbers, their conversion and type safety are available in this program.  The link is here 

Type Aliases

Type aliases define an alternative name for an existing type. You define type aliases with the typealias keyword.

For instance

typealias x=UInt8

now x can be used in place of UInt8.

var p: x=23

The type of p is now UInt8.

Tuples

Tuples group multiple values into a single compound value. The values within a tuple can be of any type and do not have to be of the same type as each other.

An example

let x=(500, “hello friends”)      // x holds two types of value (Int, String)

access the individual element values in a tuple using index numbers starting at zero:

print(” the first element’s value is \(x.0) and second element’s value is \(x.1))

It is possible to decompose the tuples value in separate constant or variables. For example

let (p, q) = x
print(p)             //output 500
print(q)            // output Hello Friends

Any permutation of types for tuples can be written like (Int, Int, String), (String, Int, Int, String). Tuples are particularly useful as the return values of functions.

Program related to typealiase and tuple can be downloaded here