Open JingchaoZhao opened 5 years ago
var shape = Shape() shape.numberOfSides = 7 var shapeDescription = shape.simpleDescription()
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."
}
}
use deinit to create a deinitializer for cleanup before the object is deallocated
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()
self super
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"
willset :todo
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.
let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square") let sideLength = optionalSquare?.sideLength
let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square") let sideLength = optionalSquare?.sideLength
class Shape { var numberOfSides = 0 func simpleDescription() -> String { return "A shape with (numberOfSides) sides." } }