Swift Basics
Swift is a new programming language for iOS, OS X, and watchOS app development
Variables
In Swift Variables will be declared with var keyword. If you provide an initial value for a variable at the point that it is declared, Swift can always infer the type to be used for that variable, otherwise we can specifically mention the type of variable.
Examples:
var speed = 60
// speed is inferred to be of type Int
var english = 90, physics = 90, chemistry = 100
// english,physics and chemistry are inferred to be of type Int
var height : Int = 6
var name : String = "John"
var red, green, blue : Double
var age : Int?
Constants
Constants will be declared with let keyword.If you provide an initial value for a constant at the point that it is declared, Swift can always infer the type to be used for that constant, otherwise we can specifically mention the type of constant.
Examples:
let maximumLogins = 15
//maximumLogins is inferred to be of type Int
let languageName : String = "Swift"
//Mentioning the constant type
let oldLanguageName : String
oldLanguageName = "Objective-C"
let constantDouble:Double = 1.0
// constantDouble = 2.0 // error
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.
Tuples are useful for temporary groups of related values. They are not suited to the creation of complex data structures. If your data structure is likely to persist beyond a temporary scope, model it as a class or structure, rather than as a tuple.
Examples:
let http404Error = (404, "Not Found")
// http404Error is of type (Int, String), and equals (404, "Not Found")
You can decompose a tuple's contents into separate constants or variables, which you then access as usual as shown below
let (statusCode, statusMessage) = http404Error
print("The status code is \(statusCode)")
// prints "The status code is 404"
print("The status message is \(statusMessage)")
// prints "The status message is Not Found"
Optionals
Use optionals in situations where a value may be absent. An optional says There is a value, and it equals x or There isn’t a value at all.
If you define an optional variable without providing a default value, the variable is automatically set to nil for you
Examples:
var surveyAnswer: String?
// surveyAnswer is automatically set to nil
Accessing Optional
if convertedNumber != nil {
print("convertedNumber has an integer value of \(convertedNumber!).")
}
In the above to access the optional we need to unwrap using !
Implicitly Unwrapped Optionals
If an optional will always have a value, after that value is first set,then it is useful to remove the need to check and unwrap the optional’s value every time it is accessed.
Examples:
var surveyAnswer: String!
// surveyAnswer is automatically set to nil
Accessing Implicitly Unwrapped Optional
if convertedNumber != nil {
print("convertedNumber has an integer value of \(convertedNumber).")
In the above to access the implicitly unwrapped optional no need to use ! as we are using in normal optionals
Operators
Assignment Operator ( = )
The assignment operator (a = b) initializes or updates the value of a with the value of b
Arithmetic Operators ( +, -, *, / )
1 + 2 // equals 3
5 - 3 // equals 2
2 * 3 // equals 6
10.0 / 2.5 // equals 4.0
Remainder Operator ( % )
9 % 4 // equals 1
Incremental and Decremental Operators ( ++ and -- )
Comparison Operators ( ==, !=, < , > , <=, >= )
1 == 1 // true, because 1 is equal to 1
2 != 1 // true, because 2 is not equal to 1
2 > 1 // true, because 2 is greater than 1
1 < 2 // true, because 1 is less than 2
1 >= 1 // true, because 1 is greater than or equal to 1
2 <= 1 // false, because 2 is not less than or equal to 1
Logical Operators ( &&, ||, ! )
Logical NOT (!a
)
Logical AND (a && b
)
Logical OR (a || b
)
Strings
A string literal is a fixed sequence of textual characters surrounded by a pair of double quotes (""
)
var fullName = "\(firstName), \(lastName)"
var tipString = "2288"
var tipInt = NSString(string: tipString).intValue
var tipDouble = NSString(string: tipString).doubleValue
Collections
Swift provides three primary collection types, known as arrays, sets, and dictionaries, for storing collections of values.
Arrays
An array stores values of the same type in an ordered list. The same value can appear in an array multiple times at different positions.
Example:
//empty array
var someInts = Array<Int>()
( or )
var someInts = [Int]()
( or )
var someInts : Int = []
//array with default values
var threeDoubles = [Double](count: 3, repeatedValue: 0.0)
//array with array literal [value1, value2, value3]
var shoppingList: [String] = ["Eggs", "Milk"]
( or )
var shoppingList = ["Eggs", "Milk"]
//accessing or modifying array
You access and modify an array through its methods and properties, or by using subscript syntax
var shoppingList = ["Eggs", "Milk"]
shoppingList.append("Flour")
// shoppingList now contains 3 items
shoppingList += ["Baking Powder"]
// shoppingList now contains 4 items
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
// shoppingList now contains 7 items
var firstItem = shoppingList[0]
// firstItem is equal to "Eggs"
shoppingList[4...6] = ["Bananas", "Apples"]
// shoppingList now contains 6 items
//To insert an item into the array at a specified index, call the array’s insert(_:atIndex:)
method:
shoppingList.insert("Maple Syrup", atIndex: 0)
//To remove an item from the array use the removeAtIndex(_:)
method
let mapleSyrup = shoppingList.removeAtIndex(0)
//Iterate over an array
for item in shoppingList { print(item) }
// prints all items in the array