swift的语法小demo2
// // main.swift // SwiftGrammarStudy // // Created by dongway on 14-6-6. // Copyright (c) 2014年 dongway. All rights reserved. // import Foundation //父类 class NamedShape{ var numberOfSides:Int = 0 var name:String init(name:String){ println("1:\(name)") self.name = name } func simpleDescription() -> String{ var simpleDescription:String = "1:A shape width \(numberOfSides) sides" println(simpleDescription) return simpleDescription } } var shape = NamedShape(name:"Martin") shape.numberOfSides = 7 var shapeDescription = shape.simpleDescription() //子类 class Square:NamedShape{ var sideLength:Double init(sideLength:Double,name: String) { self.sideLength = sideLength super.init(name:name) numberOfSides = 4 println("2:\(sideLength) \(name) \(numberOfSides)") } func area() -> Double{ var area = sideLength*sideLength println("2:area:\(area)") return area } override func simpleDescription() -> String{ var desc:String = "A shape width \(sideLength) sides" println("2:simpleDescription:\(desc)") return desc } } let test = Square(sideLength:5.0,name:"Martin") test.area() test.simpleDescription() 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 sideLength } set { println(newValue) sideLength = newValue//这里的newValue应该是个保留字,表示传入的参数值 } } override func simpleDescription() -> String { return "An equilateral triangle with sides of length \(sideLength)." } } var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle") triangle.perimeter = 9.9 //9.9传给了newValue println("\(triangle.perimeter) \(triangle.sideLength)") class TriangleAndSquare { var triangle: EquilateralTriangle { willSet { square.sideLength = newValue.sideLength } } var square: Square { willSet { triangle.sideLength = newValue.sideLength } } init(size: Double, name: String) { square = Square(sideLength: size, name: name) triangle = EquilateralTriangle(sideLength: size, name: name) } } var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape") println("3:\(triangleAndSquare.square.sideLength)") println("3:\(triangleAndSquare.triangle.sideLength)") triangleAndSquare.square = Square(sideLength: 50, name: "larger square") println("3:\(triangleAndSquare.square.sideLength)") println("3:\(triangleAndSquare.triangle.sideLength)") /* 类方法跟函数的重要区别 1,类方法调用时,第一个参数名必须省略 2,类方法可以指定两个指向同一属性的两个参数名,调用类方法时使用第一个参数名,在方法内部使用第二个参数名(不明所以) */ class Counter { var count: Int = 0 func incrementBy(amount: Int, numberOfTimes times: Int) { count += amount * times } func increment(amount:Int,times:Int){ println("4:\(times)") } } var counter = Counter() counter.incrementBy(2, numberOfTimes: 7) println("4:\(counter.count)") counter.increment(1,times:2)