This deck proposes the basic syntax for Object Oriented Programming in Swift
Define a basic struct
with initialized properties and optional properties
struct Pixel {
var positionX = 0
var positionY = 0
var height: Int?
var color: UIColor?
}
Define a basic struct with initialized properties
struct Pixel {
var positionX = 0
var positionY = 0
}
Create an instance with the standard values.
struct Pixel {
var positionX = 0
var positionY = 0
}
var myPixel = Pixel()
Access to properties
myPixel.positionX
myPixel.height
Set a value for a property
myPixel.height = 4
myPixel.color = UIColor.black
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
are ... type
struct
are value type
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)
Instance method modifying an instance property
struct Pixel {
var positionX = 0
var positionY = 0
mutating func moveOneRight() {
positionX += 1
}
}
var pixel = Pixel()
pixel.moveOneRight()
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
}
}
Inheritance. Create a subclass
class SomeSubclass: SomeSuperclass {
// properties and methods here
}
Subclassing. Overriding methods.
A subclass can modify an inherited property or method.
The new definition must have the prefix override.
Inheritance. How to access the superclass methods and properties from the subclass definition?
With the super
prefix.
super.someMethod()
super.someProperty
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).
Extension to test if a String contains the letter "a".
extension String {
var containsA: Bool {
return self.range(of: "a") != nil
}
}
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