JingchaoZhao / learning-swift

0 stars 0 forks source link

2. Objects and Classes #2

Open JingchaoZhao opened 5 years ago

JingchaoZhao commented 5 years ago

class Shape { var numberOfSides = 0 func simpleDescription() -> String { return "A shape with (numberOfSides) sides." } }

JingchaoZhao commented 5 years ago

var shape = Shape() shape.numberOfSides = 7 var shapeDescription = shape.simpleDescription()

JingchaoZhao commented 5 years ago

class with an initialiser

class NamedShape { var numberOfSides: Int = 0 var name: String

init(name: String) {
    self.name = name
}

func simpleDescription() -> String {
    return "A shape with \(numberOfSides) sides."
}

}

JingchaoZhao commented 5 years ago

use deinit to create a deinitializer for cleanup before the object is deallocated

JingchaoZhao commented 5 years ago

Subclass override the superclass's implementation.

class Square: NamedShape { var sideLength: Double

init(sideLength: Double, name: String) {
    self.sideLength = sideLength
    super.init(name: name)
    numberOfSides = 4
}

func area() -> Double {
    return sideLength * sideLength
}

override func simpleDescription() -> String {
    return "A square with sides of length \(sideLength)."
}

} let test = Square(sideLength: 5.2, name: "my test square") test.area() test.simpleDescription()

JingchaoZhao commented 5 years ago

self super

JingchaoZhao commented 5 years ago

properties that can have a getter and a setter class EquilateralTriangle: NamedShape { var sideLength: Double = 0.0

init(sideLength: Double, name: String) {
    self.sideLength = sideLength
    super.init(name: name)
    numberOfSides = 3
}

var perimeter: Double {
    get {
        return 3.0 * sideLength
    }
    set {
        sideLength = newValue / 3.0
    }
}

override func simpleDescription() -> String {
    return "An equilateral triangle with sides of length \(sideLength)."
}

} var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle") print(triangle.perimeter) // Prints "9.3" triangle.perimeter = 9.9 print(triangle.sideLength) // Prints "3.3000000000000003"

JingchaoZhao commented 5 years ago

willset :todo

JingchaoZhao commented 5 years ago

working with optional values, you can write ? before operations like methods, properties, and subscripting. if the value before the ? is nil, everything after the ? is ignored and the value of the whole expression is nil. Otherwise, the optional value is uwrapped and everyting after the ? acts on the unwrapped value. In both cases, the value of the whole expression is an optional value.

JingchaoZhao commented 5 years ago

let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square") let sideLength = optionalSquare?.sideLength

JingchaoZhao commented 5 years ago

let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square") let sideLength = optionalSquare?.sideLength