Swift is 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 to 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 variable needs var.
- Swift uses type inference.
- Supports unicode characters. You can use any character as variable.
- Prefer usage of constant (let) for immutable than using var.
- Optional variables can contain value or nil. – var givenName : String? = “Ravi”
- Swift’s Switch supports all kinds of datatype and operations and does not need a break statement 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.
- Supports Optional Binding and Optional Chaining
Variables and Constants
[code language=”swift”]
// Variables and Constants
var myStr = "Swift"
var myValue = 23.1 //(Implicit variable declaration or type inference)
var myDoubleValue: Double = 23 //(Explicit variable declaration)
// let
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 or interpolation)
[/code]
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
Fun with String
[code language=”swift”]// String
var movie:String = "Independence Day "
count(movie) // count of string
// Use NSString to format a double or float value
var range = NSString(format: "%.2f", 24.5)
// Concatenate String values
movie += String(range)[/code]
Collection Types
Array
[code language=”swift”]// Declarations
// var fruits = ["Orange", "Apple", "Grapes"] – Short declartion
// var fruits:Array = ["Orange", "Apple", "Grapes"] – Long declaration
// var fruits:[String] = [] – Assign empty array
var fruits:[String] = ["Orange", "Apple", "Grapes"] // short declaration with type.
// insert item at index
fruits.insert("Mangoes", atIndex: 2)
// append item to the last
fruits.append("Pine Apple")
// count of array
fruits.count
// remove item
fruits.removeAtIndex(1)
// sort array elements
fruits.sort { (a, b) -> Bool in
a < b
}
// retrieve index using find
find(fruits, "Mangoes")
[/code]
Dictionary
[code language=”swift”]// Dicionary
// Declaration
// var employees = [1:"John",2:"Peter",3:"David"] // Short form
// var employees:Dictionary = [1:"John",2:"Peter",3:"David"] // Long form
// var employees:[Int:String] = Dictionary() // Empty dictionary
var employees:[Int:String] = [1:"John",2:"Peter",3:"David"] //Short form with type
// Add new item to dictionary
employees[4] = "Bob"
// Remove an item using key
employees.removeValueForKey(3)
[/code]
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 AssignmentOperator
- x += 2 is same as x = x + 2.
ComparisonOperators
- 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).
RangeOperators
- 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
LogicalOperators
- NOT ( !x )
- AND ( x && y )
- OR ( x || y )
Control Flow
[code language=”swift”]// Control flow
// if else
if fruits[0] == "Grapes" {
println("for breakfast")
} else if fruits[0] == "Apple" {
println("for lunch")
} else {
println("Nothing")
}
// for statements
// exclusive range
for index in 0..<h3><u>Comments</u></h3>[code language="swift"] Single line comments // examples
Multiline comments /* example1
example2 */
[/code]
Function
[code language=”swift”]func sum(number1:Int, number2: Int) -> (Int) {
return number1 + number2
}[/code]
The above function is an example of multiple input parameters. It does the addition of two numbers where number1 and number are arguments of type Int and it returns a value of type int. And a function without parameter looks like this.
[code language=”swift”]
func sum() -> (Int) {
return 10 + 5
}[/code]
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
[code language=”swift”]func sum(addNumber1 number1:Int, withNumber2 number2: Int) -> (Int) {
return number1 + number2
}
println(sum(addNumber1: 10, withNumber2: 20))
[/code]
addNumber1 and withNumber are external parameter names for two parameters. And you use # to tell local and external parameter name are same.
[code language=”swift”]
func sum(#number1:Int, #withNumber2: Int) -> (Int) {
return number1 + withNumber2
}
println(sum(number1: 10, withNumber2: 20))[/code]
Function with default parameter value
[code language=”swift”]func sum(number1:Int, withNumber2: Int = 20) -> (Int) {
return number1 + withNumber2
}
println(sum(10))[/code]
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.
[code language=”swift”]
// Variadic parameters
func totalSum(numbers:Int…) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
totalSum(1,2,3,4,5)[/code]
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.
[code language=”swift”]
// inout parameters
var employee = "Ravi"
func greetings(inout employee:String) {
employee += "!"
}
println(greetings(&employee))
println(&employee)[/code]