Swift3.0基础语法学习<二>
对象和类:
1 // 2 // ViewController2.swift 3 // SwiftBasicDemo 4 // 5 // Created by 思 彭 on 16/11/15. 6 // Copyright © 2016年 思 彭. All rights reserved. 7 // 8 9 import UIKit 10 11 class ViewController2: UIViewController { 12 13 override func viewDidLoad() { 14 super.viewDidLoad() 15 self.title = "基本语法《二》" 16 17 // 1.对象和类 18 var shape = Shape() 19 shape.numberOfSides = 7 20 var shapeDescription = shape.simpleDescription() 21 print(shapeDescription) 22 23 // 2.初始化创建类,init创建 24 var nameShape = NameShape(name: "Sisi") 25 print(nameShape.name) 26 27 // 3.子类,继承关系 28 let test = Square(sidelength: 5.0, name: "HaHa") 29 print("area = \(test.area())") 30 print(test.simpleDescription()) 31 32 // 4. set方法 33 var traig = TriangleAndSquare(size: 55, name: "xixix") 34 print(traig.size) 35 print(traig.triangle) 36 } 37 } 38 39 // 定义类 40 class Shape { 41 42 var numberOfSides = 0 43 func simpleDescription() -> String { 44 45 return "A shape with \(numberOfSides) sides." 46 } 47 } 48 49 // 带初始化方法的类 50 class NameShape { 51 52 var numberOfSides: Int = 0 53 var name: String 54 init(name: String) { 55 self.name = name 56 } 57 58 func simpleDescription() -> String { 59 60 return "A shape with \(numberOfSides) sides." 61 } 62 } 63 64 // 继承父类的子类 65 class Square: NameShape { 66 67 var sideLength: Double 68 69 init(sidelength: Double, name: String) { 70 self.sideLength = sidelength 71 super.init(name: name) 72 numberOfSides = 4 73 } 74 75 func area() -> Double { 76 77 return sideLength * sideLength 78 } 79 // 重写父类方法 80 override func simpleDescription() -> String { 81 82 return "A square with sides of length \(sideLength)." 83 } 84 } 85 86 // set方法 87 class TriangleAndSquare { 88 89 var size: Double = 0.0 90 var triangle: Square { 91 92 willSet { 93 94 print(triangle.simpleDescription()) 95 } 96 } 97 init(size: Double, name: String) { 98 triangle = Square(sidelength: size, name: name) 99 self.size = size 100 } 101 }