Details for a topic

Object Oriented Programming in Swift : struct, class

This deck proposes the basic syntax for Object Oriented Programming in Swift

All cards

struct

Define a basic struct with initialized properties and optional properties

struct Pixel {
    var positionX = 0
    var positionY = 0
    var height: Int?
    var color: UIColor?
}

struct

Define a basic struct with initialized properties

struct Pixel {
var positionX = 0
var positionY = 0
}

struct

Create an instance with the standard values.

struct Pixel {
var positionX = 0
var positionY = 0
}
var myPixel = Pixel()

struct and class

Access to properties

myPixel.positionX
myPixel.height

struct and class

Set a value for a property

myPixel.height = 4
myPixel.color = UIColor.black

struct

Create an instance of struct with the standard initializer.

struct Pixel {
var positionX: Int
var positionY: Int
}
let myPixel = Pixel(positionX: 4, positionY: 2)

struct

struct are ... type

struct are value type


struct

Computed properties for a struct

struct Pixel {
    var positionX : Int
    var positionY : Int
    var distanceToCenter : Double {
        return sqrt(Double(positionX^2 + positionY^2))
    }
}
let myPixel = Pixel(positionX: 7, positionY: 4)
print(myPixel.distanceToCenter)

struct

Instance method modifying an instance property

struct Pixel {
    var positionX = 0
    var positionY = 0
    mutating func moveOneRight() {
        positionX += 1
}
}
var pixel = Pixel()
pixel.moveOneRight()
   

class

Create a simple class with initializer

class Point {
    var posX: Float
    var posY: Float
var color: UIColor?
    init (x: Float, y: Float) {
        self.posX = x
        self.posY = y
    }
}

class

Inheritance. Create a subclass

class SomeSubclass: SomeSuperclass {
// properties and methods here
}

class

Subclassing. Overriding methods.

A subclass can modify an inherited property or method.

The new definition must have the prefix override.


class

Inheritance. How to access the superclass methods and properties from the subclass definition?

With the super prefix. 

super.someMethod()
super.someProperty

Extensions

What are extensions?

Extensions add new functionality to an existing class, structure, enumeration, or protocol type.

This includes types to which one does not have access. (ex: Int, String).


Extensions

Extension to test if a String contains the letter "a".

extension String {    
var containsA: Bool {
return self.range(of: "a") != nil
}
}

Extensions

Extension to add a given Int to an Int.

extension Int {
    func plusX(x: Int)->Int {
        return self + x
    }
}
2.plus(x: 3) //is 5

An extension can modify the value of the variable.

Example of an extension to add 1 to an Int.

extension Int {
    mutating func plus1() {
        self += 1
    }
}
let number = 2
number.plus1()
number // is 3