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

Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *