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.
ICT role in 21st century education and its challenges
Swift as an OOP Language
1. SWIFT AS AN OOP LANGUAGE
iOS Development using Swift
Ahmed Ali
2. TODAY TOPICS
• Classes and Structures
• Properties
• Methods
• Access Control
• Inheritance
• Initialization
• Deinitialization
• Protocols
• Transitions and View Controller Lifecycle Demo
Ahmed Ali
3. 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]
4. CLASSES AND STRUCTURES (CONT)
• Only classes can:
• Inherit from another class
• Define deinit method
• Type casted
Ahmed Ali
5. CLASSES AND STRUCTURES (CONT)
• 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()
Ahmed Ali
6. 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
7. • 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
8. 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
9. 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
10. 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
11. 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
12. 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
13. 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
14. 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
15. 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
16. 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
17. 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
19. 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
20. 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
21. 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
22. INHERITANCE (CONT)
• Base class example:
class BaseClass
{
var computedProperty : String{
get{ return ”BaseClass property” } set{
println(newValue)
}
}
func printClassName()
{
println("BaseClass")
}
}
Ahmed Ali
23. INHERITANCE (CONT)
• Inheritance example:
class Subclass : BaseClass
{
}
Ahmed Ali
24. 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
25. 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
26. 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
27. 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
28. 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
29. 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
30. 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
31. 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
32. 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
33. INITIALIZATION – INITIALIZERS (CONT)
Designated Convenience
• 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.
Ahmed Ali
Types of initializers: designated and convenience.
34. INITIALIZATION – INITIALIZERS (CONT)
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")
}
}
Ahmed Ali
Example:
35. 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
36. 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
37. 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
38. 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
39. 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
40. 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