Swift QuickReference 1

Swift the latest programming language released by Apple for developing OS X and iOS apps.

  • Best of C and Objective-C
  • Adopts safe programming patterns and modern features
  • Supports playground, a tool for seeing the result immediately.
  • Provides access to Cocoa libraries and can work in conjunction with Objective-C
  • Combines Procedural and Object-Oriented programming.
  • No need use semicolon at the end of statement. Use it only when you have more than one statement in single line.
  • Swift uses var and let. only mutable needs to be used var. Safe Modern, Power. Swift uses type inference. Use unicode character for name.
  • Prefers usage of constant (let) for immutable than using var.
  • You can use any character as variable.
  • Optional variables can contain value or nil. – var givenName : String? = “Ravi
  • Switch supports all kinds of datatype and operations and does need to add break after each case statement.
  • No need to enclose your expression in brackets with if statements
  • Swift function supports default value for the parameter and variable parameter.
  • Closures are like blocks in Objective-C ( ) -> ( )
  • No need to specify header file in Swift
  • No need to specify base class and there is no universal base class
  • No difference between instance variable and properties
  • Tuples – Grouping of multiple values.
  • Nested multiline comments are allowed.
  • Use typealias to provide different name to an existing type.
  • Swift nil represents absence of value and objective – C nil represents pointer to a non-existent object.
  • Implicitly unwrapped optional let pincode : String! = “E151EH”
  • Provides Assertion to end code execution where certain criteria is not met.
  • Swift’s String is value type and not passed by reference.
  • Optional Bindings

Variables and Constants

var myStr = “Swift”

let message = “Hello World”

let myValue = 23.1 (Implicit variable declaration)

let myDoubleValue: Double = 23 (Explicit variable declaration)

let myAge = 38

let message = “My age is “ + String(myAge) (Converting value to a String)

let newMessage = “My age is \(myAge) (Converting value to a String using backslash)

Data types in Swift

String

Int (Range -2,147,483,648 to 2,147,483,648)

Double (15 digit precision)

Float (6 digit precision)

Bool

Assignment Operator

  • a = b
  • let (a,b) = (2,3) – supports tuple.
  • Does not return value.

Arithmetic Operators

  • Addition (+), Subtraction (-), Multiplication (*), Division (/)
  • + can be used for string concatenation.
  • % – Returns remainder for both +ve and -ve numbers. Also returns remainder for floating point numbers.
  • Increment and Decrement operators, ++i (i = i + 1), —i (i = i – 1).
  • Supports i++ and i— (increments or decrements after returning the value).
  • Unary Minus and Unary Plus

Compound Assignment Operator

  • x += 2 is same as x = x + 2.

Comparison Operators

  • x == y
  • x != y
  • x > y
  • x < y
  • x >= y
  • x <= y
  • === and !== used for testing object references.

Ternary Conditional Operator

  • a = flag ? 10 : 20 (if flag is true then a will updated to 10 and 20 incase it is false).

Range Operators

  • Closed Range – e.g.:- 1…10, has three dots and includes values from 1 to 10.
  • Half Closed – e.g.:- 1..10, has two dots and includes values from 1 to 9

Logical Operators

  • NOT ( !x )
  • AND ( x && y )
  • OR ( x || y )
Collection Types

Array

var fruits = [“Apples”, “Oranges”, “Grapes”]

fruits[1] = “Pine Apples”

strArray.isEmpty //check if array is empty

strArray.append(”!”) //insert element at end of array

strArray += (”!”) //insert element at end of array

strArray = [] //empty

var addArrays = strArray + strNames //Add two arrays

var strNames:Character[] = Character[](count:2,repeatedValue:“a”) //Array with pre-defined size and default values

strArray.insert(”!”, atIndex: 0) //insert element at specified index

strArray.removeAtIndex(0) //remove element at specified index

strArray.removeLast() //remove last element

Dictionary

var expEmployees:Dictionary<Int,String> = [1:“Ravi”, 2:“Rajesh”] //Explicitly specify the type for key and value

var employees = [1:“Ravi”, 2:“Rajesh”] // Infer type of Keys and values

employees[“John”] = “Web Developer” // Add another element to the dictionary

employees.updateValue(“Rakesh”, forKey:1) // Update a value using key.

employees.removeAll(keepCapacity: false) //remove elements

employees.removeValueForKey(1) //remove value based on key

employees = [:] //make it empty

for (no,name) in employees {

}

for (no) in employees.keys {

}

for (name) in employees.values {

}

Control Flow

if salary {} incorrect, if salary > 40000 correct, expression should return a boolean value.

for statement with and without upper value

for i in 0..3 denotes that i does not include upper value 3.

for i in 0…3 denotes that i includes upper value

Comments
Single line comments // examples

Multiline comments /* example1

example2 */

Function

func <function_name> (<argument>:<argument_type) -> <return parameter> {

}

func sum(number1:Int, number2: Int) -> (Int) {

return number1 + number2

}

The above function is an example of multiple input parameters. It does the addition of two numbers. number1 and number are arguments of type Int and it returns a value of type int. And a function without parameter looks like this.

func sum() -> (Int) {

return 10 + 5

}

The above function is an example of multiple input parameters. It does the addition of two numbers. number1 and number are arguments of type Int and it returns a value of type int. And a function without parameter looks like this. Swift function can also have multiple return values.

Define external parameter name

func sum(addNumber1 number1:Int, withNumber2 number2: Int) -> (Int) {

return number1 + number2

}

println(sum(addNumber1: 10, withNumber2: 20))

Define addNumber1 and withNumber are external parameter names for two parameters. Use # to tell local and external parameter name are same.

func sum(#number1:Int, #withnumber2: Int) -> (Int) {

return number1 + withnumber2

}

println(sum(number1: 10, withnumber2: 20))

Function with default parameter value

func sum(number1:Int, withnumber2: Int = 20) -> (Int) {

return number1 + withnumber2

}

println(sum(10))

The above function has default value for the second parameter.

Variadic Parameters

A function with variadic parameters can accept zero or more values. Maximum of one parameter is allowed in a function and it is always last in the list.

Variable and inout parameters

Variable parameters in a function are indicated by var keyword and the scope is available only within the function. If you want to access the modified variable value outside the function then you specify them as inout parameter. And prefix with & while passing the parameter in the function call.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s