04 - Swift Recap

In this section, we talked about Swift and got started with actually coding in Swift. In particular, we covered the following basic matters:


  • Swift Basics

  • Swift Playground

  • Swift Strings

  • Collections in Swift (Arrays and Dictionaries)

  • Functions in Swift


Playground

A playground is the learning environment of XCode for Swift. You could use it on both your Mac as well as on your iPad.


Swift Variables

Next important topic is the variable in Swift. We have several different matters to keep in mind:

  • Let for introducing immutable variables. Let example is Objective-C is NSArray

  • Var for introducing mutable variables. Var example is Objective-C is NSMutableArray

  • Type Annotations

  • In Swift, we could use the type annotations to explicitly define the type of a variable.

  • Writing comments are similar to those in Objective-C

  • Semicolons are not necessary for Swift.

  • String Interpolation print ("\(myFloat)")



Swift Options

Swift options are a rather important topic.  If a variable is optional, it can be nil. Otherwise, it must have a value.

  • var optionalString: String? // which can be nil

  • var nonOptionalString: String = "Hello" // Which Must have a value

  • var unWrappedString: String! // implicitly unwrapped optional. Implicitly unwrapped optionals are useful when an optional value is confirmed to exist. ! lets you treat the property as if it were non-optional


You can do force unwrapping by ! . It's not the safest thing to do though

 var n : Int?
 print ("\(n!)")

Conditional Unwrapping


 var someVar : Int?
 if let val = someVar // you can also use the same name
 {
 print ("\(val)")
 }
 else
 {
 print ("nada");
 }

Type casting for unwrapping


 var someVal: Any? = 1
 if someVal as? String != nil {
 print("This is string")
 }
 if someVal as? Int != nil {
 print("Int's Int")
 }



Link for further study: https://docs.swift.org/swift-book/LanguageGuide/OptionalChaining.html




Swift Control Flow


If Else

In an If Statement, we don't need the round brackets, but the curly brackets for the statement are necessary


If n == true {

}


Switch

The break statement inside a switch can be used when you don't need a case to have any actual functionality.


for

In a for loop, you shouldn't use round brackets and the numbering is different. For an example


for any in "Ding"
{
print ("\(any)")
}

Repeat While and While are exactly identical to Do While and While


Swift Strings

let someString = "Some string literal value"
let multilineString = """
These are the same.
"""
var variableString = "Horse"
variableString += " and carriage"
if quotation == sameQuotation {
	print("These two strings are considered equal")
}


Read further at:

https://docs.swift.org/swift-book/LanguageGuide/StringsAndCharacters.html


Swift Arrays

Arrays in swift are rather simplified

var myArray : Array <String> = ["Hello", "World", "Swift", "iOS"]
print ("\(myArray)")
myArray.remove(at: 1)
print ("\(myArray)")
myArray.append("ObjC")
print ("\(myArray)")

You can use Any for arrays where the type is not predetermined
 
 var myArray : Array <String> = ["Hello", "World", "Swift", "iOS"]
 if let index = myArray.index(of: "Hello") {
 print("Found Hello at index \(index)")
 }

You can still use the NSArray if you prefer, but you cannot explicitly select its type


var myNsArr : NSMutableArray = NSMutableArray.init(objects: "Hi", "World");

myNsArr.index(of: "Hi")




Swift Dictionaries

Dictionaries in Swift are rather simplified and powerful. We declare dictionaries by a var or let of the type dictionary and then we can explicitly mention the type of the values in that dictionary.


We could also let the types be inferred from the values.

Once we have a dictionary, we can add new key-value pairs to it or update them.

For iterating within a dictionary, we rely on tuples. Tuples are a powerful ordered set of values. The values can be accessed by index or by name.


var person = ("John", "Smith")

var firstName = person.0 // John
var lastName = person.1 // Smith
var person2 = (firstName: "John", lastName: "Smith")
var firstName = person2.firstName // John
var lastName = person.1 // Smith

var namesOfIntegers = [Int: String]()
namesOfIntegers[16] = "sixteen"



var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
// Or
var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

airports["LHR"] = "London"

for (airportCode, airportName) in airports 
{
print("\(airportCode): \(airportName)")
}


Swift Functions

Swift functions are written in a slightly different format than that of Objective-C.


func myFunc (inp: String) -> (name: String, res: Int)
{
	return ("Hello " + inp, 2)
}

myFunc (inp: "Amir")

We can also nest functions inside one another

func nestedFunc ()
{
	func internalFunc () -> String
	{
    	return "yo"
	}
	print ( internalFunc() )
}
nestedFunc()


Swift in iOS

We no longer have a .h and .m file. Everything is in one place