Swift编程语言入门教程

2020-01-08 22:44:24王旭

    }
    }
 
    var square: Square {
    willSet {
        triangle.sideLength = newValue.sideLength
    }
    }
 
    init(size: Double, name: String) {
        square = Square(sideLength: size, name: name)
        triangle = EquilaterTriangle(sideLength: size, name: name)
    }
}
var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")
triangleAndSquare.square.sideLength
triangleAndSquare.triangle.sideLength
triangleAndSquare.square = Square(sideLength: 50, name: "larger square")
triangleAndSquare.triangle.sideLength

 

类的方法与函数有个重要的区别。函数的参数名仅用与函数,但方法的参数名也可以用于调用方法(除了第一个参数)。缺省时,一个方法有一个同名的参数,调用时就是参数本身。你可以指定第二个名字,在方法内部使用。

 

复制代码
class Counter {
    var count: Int = 0
    func incrementBy(amount: Int, numberOfTimes times: Int) {
        count += amount * times
    }
}
var counter = Counter()
counter.incrementBy(2, numberOfTimes: 7)

 

当与可选值一起工作时,你可以写 "?" 到操作符之前类似于方法属性。如果值在"?"之前就已经是 nil ,所有在 "?" 之后的都会自动忽略,而整个表达式是 nil 。另外,可选值是未包装的,所有 "?" 之后的都作为未包装的值。在两种情况中,整个表达式的值是可选值。

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

7   枚举与结构
使用 enum 来创建枚举。有如类和其他命名类型,枚举可以有方法。

 

复制代码
enum Rank: Int {
    case Ace = 1
    case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
    case Jack, Queen, King
    func simpleDescrition() -> String {
        switch self {