41
iOS Development using Swift SWIFT AS AN OOP LANGUAGE Ahmed Ali

Swift as an OOP Language

Embed Size (px)

DESCRIPTION

Learning iOS development using Swift (Arabic tutorials) - Third session slides, which covers the following topics: - Classes and Structures - Properties - Methods - Access Control - Inheritance - Initialization - Deinitialization - Protocols The video concludes with a demo of screen transitions and view controller lifecycle.

Citation preview

Page 1: Swift as an OOP Language

iOS Development using Swift

SWIFT AS AN OOP LANGUAGE

Ahmed Ali

Page 2: Swift as an OOP Language

TODAY TOPICS

• Classes and Structures

• Properties

• Methods

• Access Control

• Inheritance

• Initialization

• Deinitialization

• Protocols

• Transitions and View Controller Lifecycle Demo

Ahmed Ali

Page 3: Swift as an OOP Language

CLASSES AND STRUCTURES

• Both can:

• Define properties to store values

• Define methods to provide functionality

• Define subscripts

• Define initializers

• Can be extended (not subclassed, only a class can have a subclass)

• Conform to protocols

Ahmed Ali

ref["key”] anotherRef[1]

Page 4: Swift as an OOP Language

CLASSES AND STRUCTURES (CONT)

• Only classes can:

• Inherit from another class

• Define deinit method

• Type casted

Ahmed Ali

Page 5: Swift as an OOP Language

• Class vs Structure

• Definition Syntax:

• Classes passed by reference, while structures are passed by value. Structures called value types for that reason.

• Create instance:

class SomeClass

{

}

struct SomeStruct

{

}

let someClass = SomeClass()

let someStruct = SomeStruct()

CLASSES AND STRUCTURES (CONT)

Ahmed Ali

Page 6: Swift as an OOP Language

PROPERTIES• Properties associate values with particular type’s instances.

• Properties can be a variable or a constant

• There are two main types of properties:

• Stored Properties

• Computed Properties

Ahmed Ali

Page 7: Swift as an OOP Language

• Stored properties just store the values, while computed properties compute their values.

• Example of stored properties:

• No initial value for non optional?

struct Point

{

var x : Float

var y : Float

}

struct Size

{

var width : Float

var height : Float

}

PROPERTIES (CONT)

Ahmed Ali

Page 8: Swift as an OOP Language

PROPERTIES (CONT)• Example of computed properties:struct Rect

{

var origin = Point(x: 0, y: 0), size = Size(width: 50, height: 50)

var center : Point{

get{

return Point(x: origin.x + (size.width * 0.5), y: origin.y + (size.height * 0.5))

}

set{

origin.x = newValue.x - (size.width * 0.5)

origin.y = newValue.y - (size.height * 0.5)

}

}

}

Ahmed Ali

Page 9: Swift as an OOP Language

PROPERTIES (CONT)• Both types of properties are accessible and modifiable in the same manner, using the dot

syntax.

• Computed properties calculated every time you access them.

//If a structure reference is defined as a constant, we will not be able to change any of its properties

var rect = Rect()

let centerPoint = rect.center

let origin = rect.origin

//modifying their values

rect.origin.x = 50

rect.center = Point(x: 100, y: 100)

Ahmed Ali

Page 10: Swift as an OOP Language

PROPERTIES (CONT)• Property observers:

• didSet, willSet

• Syntax:struct Point

{

var x : Float{

didSet{

println("The value of x has been changed from \(oldValue) to \(x)")

}

willSet{

println("The value of x has been changed from \(x) to \(newValue)")

}

}

var y : Float

}

Ahmed Ali

Page 11: Swift as an OOP Language

METHODS• Methods are used to provide functionality associated with a specific type.

• Methods can have:

• One or more parameter.

• A return value of any type.

• Can have external parameter names, for better readability.

• Definition Syntax:

class SomeClass{

func methodName(param1 : String) -> Int?

{

//countElements is a global function that returns the string length

return countElements(param1)

}

}

Ahmed Ali

Page 12: Swift as an OOP Language

METHODS (CONT)• External parameter name, promising better readability for your method users.

• Method call without external parameter names:

let view = View()

Animator.moveView(view, Point(0, 0), Point(50, 50))

Ahmed Ali

Page 13: Swift as an OOP Language

METHODS (CONT)• Method call with external parameter names:

let view = View()

Animator.moveView(view, fromPoint: Point(x:0, y:0), toPoint: Point(x: 50, y: 50))

Ahmed Ali

Page 14: Swift as an OOP Language

METHODS (CONT)• Defining parameter external name:

struct Math

{

static func powerOfNumber(baseNumber: Int, toPower power: UInt) -> Int

{

var total = 0

for i in 2 ... power

{

total += (baseNumber * baseNumber)

}

return total

}

}

let value = Math.powerOfNumber(2, toPower: 3)

Ahmed Ali

Page 15: Swift as an OOP Language

METHODS (CONT)• You can override this external name behavior if it does not make sense:

struct Math

{

static func powerOfNumber(baseNumber: Int, _ power: UInt) -> Int

{

var total = 0

for i in 2 ... power

{

total += (baseNumber * baseNumber)

}

return total

}

}

let value = Math.powerOfNumber(2, 3)

Ahmed Ali

Page 16: Swift as an OOP Language

METHODS (CONT)• You can create static methods which can be access without the need to create an

instance.

• Example:

struct Math

{

static func add(x : Int, _ y : Int) ->Int

{

return x + y

}

}

println("5 + 6 = \(Math.add(5, 6))")

Ahmed Ali

Page 17: Swift as an OOP Language

METHODS (CONT)• For value types, you can not change any property inside any method.

• If a method will change any property value, it must be marked as a mutating method.

• Mutating method can not be called on any constant reference.

• Example:

struct SomeStruct{

var property : String

mutating func changeProperty(newValue : String)

{

property = newValue

}

}

let s = SomeStruct(property: "value")

//invalid because s is a constant

s.changeProperty("new value")

Ahmed Ali

Page 18: Swift as an OOP Language

ACCESS CONTROL

Modules vs Source Files

Ahmed Ali

Page 19: Swift as an OOP Language

ACCESS CONTROL (CONT)• Access Levels

• Public: Accessible everywhere.

• Internal: Accessible for any source code file in defining module.

• Private: Accessible only in the same source code file.

• Internal is the default access level.

Ahmed Ali

Page 20: Swift as an OOP Language

ACCESS CONTROL (CONT)• Syntax:

public class SomeClass

{

private var myVar = "My Var Value"

internal var myInt = 5

public func calc() -> String

{

return "\(myVar) => \(myInt)"

}

}

Ahmed Ali

Page 21: Swift as an OOP Language

INHERITANCE• No universal base class that all other classes inherit from.

• Any class who has no super class, is known to be a base class.

• You can override super class methods and computed properties using the override keyword.

• You can not override stored properties of super class, but you can observe them.

Ahmed Ali

Page 22: Swift as an OOP Language

INHERITANCE (CONT)• Base class example:class BaseClass

{

var computedProperty : String{

get{ return ”BaseClass property” } set{

println(newValue)

}

}

func printClassName()

{

println("BaseClass")

}

}

Ahmed Ali

Page 23: Swift as an OOP Language

INHERITANCE (CONT)• Inheritance example:

class Subclass : BaseClass

{

}

Ahmed Ali

Page 24: Swift as an OOP Language

INHERITANCE (CONT)• Overriding computed property example:class Subclass : BaseClass

{

override var computedProperty : String

{

get{

return "Subclass property"

}

set{

println("Setting the property in the subclass")

}

}

}

Ahmed Ali

Page 25: Swift as an OOP Language

INHERITANCE (CONT)• Overriding a method example:

class Subclass : BaseClass

{

override func printClassName()

{

//you can also call the original method

//which were defined in the super class

super.printClassName()

println("Subclass")

}

}

Ahmed Ali

Page 26: Swift as an OOP Language

INITIALIZATION• Initialization is the process of creating a new instance.

• Mainly used to set non-optional properties’ values and any initial setup.

• The initialization process can not be completed while any non-optional properties still have no value.

• Implementation is done through special methods called initializers.

Ahmed Ali

Page 27: Swift as an OOP Language

INITIALIZATION - INITIALIZERS• An initializer is a normal method, with little different syntax.

• Initializer method is always called “init”

• You don’t write the “func” keyword before the initializer.

• Initializers always return nothing.

• Can take zero or more parameters.

• Class can have zero or more initializers.

• An initializer is required if any of your non-optional properties have no default value.

Ahmed Ali

Page 28: Swift as an OOP Language

INITIALIZATION – INITIALIZERS (CONT)• Initializer example:

class SomeClass

{

//because we do not provide the property's initial value here

//we must provide its value in the initializer

var strProperty : String

init()

{

//If you have any property observers, they will not be called during the initial value assignment

strProperty = "Initial value"

}

}

Ahmed Ali

Page 29: Swift as an OOP Language

INITIALIZATION – INITIALIZERS (CONT)• You can create custom initializer that takes one or more parameter.

• Unlike methods, all initializer’s parameters have external names by default.

• Example:

class SomeClass

{

var strProperty : String

init(strProperty: String)

{

self.strProperty = strProperty

}

}

Ahmed Ali

Page 30: Swift as an OOP Language

INITIALIZATION – INITIALIZERS (CONT)• Default initializer (that takes no parameters) is automatically available if and only if:

1. All your non-optional properties have default values and you did not create any initializers at all.

• Constant property value can be modified in any initializer. However, you can not modify super class’s constant property in a subclass initializer.

Ahmed Ali

Page 31: Swift as an OOP Language

INITIALIZATION – INITIALIZERS (CONT)• Create an instance the default initializer:

let someClass = SomeClass()

• Create an instance with custom initializer:

let someClass = SomeClass(strProperty: "String value")

Ahmed Ali

Page 32: Swift as an OOP Language

INITIALIZATION – INITIALIZERS (CONT)• In structure types, if you have not defined any initializer, a member-wise initializer is

automatically created for you.

• Example:

struct Point

{

var x : Float

var y : Float

}

Now you can create instances of the Point type using its auto-created member-wise initializer as follows:

let point = Point(x: 15, y: 20)

Ahmed Ali

Page 33: Swift as an OOP Language

• Provides a more convenience initializer.

• Must end up calling a designated initializer.

• Syntax - add “conveniece” keyword before “init”. Example:

convenience init()

{

}

• All non-optional properties’ values are assigned before it is finished.

• For classes, it must call the super class designated initializer if defined in a subclass.

• Syntax - any initializer you defined before with “init” is a designated initializer.

INITIALIZATION – INITIALIZERS (CONT)

Designated Convenience

Ahmed Ali

Types of initializers: designated and convenience.

Page 34: Swift as an OOP Language

class BaseClass{ var str : String var str2 : String init(str : String, str2: String) { self.str = str self.str2 = str2 } convenience init(str: String) {self.init(str: str, str2: "String 2") }}

class Subclass : BaseClass

{

var substr : String

init(substr : String)

{

self.substr = substr

super.init(str:substr, str2: "none")

}

}

INITIALIZATION – INITIALIZERS (CONT)

Ahmed Ali

Example:

Page 35: Swift as an OOP Language

DEINITIALIZATION• Deinitlization is the process of making any final clean-up before removing a class’s

instance from the memory.

• You just need to implement a special method called deinit which takes no parameters and returns nothing.

• Example:

deinit{

//Your clean up code goes here

}

Ahmed Ali

Page 36: Swift as an OOP Language

PROTOCOLS• A protocol defines set of properties and methods, not their implementation.

• Any class, structure or enumeration can conform to any number of protocols.

• When a type is said to be conforming to a protocol, it means: this type provides the actual implementation for that protocol.

• Definition syntax:

protocol SomeProtocol

{

//read and write property

var neededProperty : String {get set}

//read-only property

var anotherProperty : String {get}

func requiredMethod() -> (String, String)

}

Ahmed Ali

Page 37: Swift as an OOP Language

PROTOCOLS• Syntax for defining a type which conforms to a protocol:

struct SomeStruct : SomeProtocol{

var neededProperty : String

var anotherProperty : String

func requiredMethod() -> (String, String) {

return ("V1", "V2")

}

}

Ahmed Ali

Page 38: Swift as an OOP Language

PROTOCOLS• If the type is a class, and it also subclass another class, the super class name comes first

in the list.

• Example:

class Subclass : BaseClass, SomeProtocol, AnotherProtocol{

var neededProperty : String

var anotherProperty : String

func requiredMethod() -> (String, String) {

return ("V1", "V2")

}

}

Ahmed Ali

Page 39: Swift as an OOP Language

PROTOCOLS• Protocols can be used as a type. That is, you can define any reference with the type of a

protocol instead of a concrete type.

• Example:

struct SomeStruct

{

var property : SomeProtocol

func method(param1 : AnotherProtocol)

{

}

}

Ahmed Ali

Page 40: Swift as an OOP Language

PROTOCOLS• You can also define a reference to be any type that conforms to more than one protocol

• Example:

struct SomeStruct{

var property : protocol<SomeProtocol, AnotherProtocol>

}

Ahmed Ali

Page 41: Swift as an OOP Language

Ahmed Ali

Transitions and View Controller Lifecycle Demo