SWfit学习3:类和对象
创建和使用类 Swift 使用 class 创建一个类,类可以包含字段和方法: class Shape {
var numberOfSides = 0
func simpleDescription() -> String
{
return "A shape withh (numberOfSides) sides."
}
}
?创建 Shape 类的实例,并调用其字段和方法 var shapes = Shape()
shapes.numberOfSides = 10
shapes.simpleDescription()
println("(shapes.simpleDescription())")
通过 init 构建对象,既可以使用 self 显式引用成员字段(name),也可以隐 式引用(numberOfSides)。 class NamedShape {
var numberOfSides: Int = 0
var name:String
init(name:String)
{
self.name = name
}
func simpleDescription()-> String
{
return "A shape with (numberOfSides) sides"
}
}
let nameShape = NamedShape(name:"haha")
nameShape.numberOfSides = 10
nameShape.simpleDescription()
println("(nameShape.simpleDescription())")
继承和多态 Swift 支持继承和多态(override 父类方法): 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
}
let test = Square(sideLength: 5.2,name: "my test square")
test.area()
test.simpleDescription()
注意:如果这里的 simpleDescription 方法没有被标识为 override 错误。 属性 为了简化代码,Swift 引入了属性(property),见下面的 perimeter 字段: 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{
println("sideLength = (sideLength)")
return sideLength
}
set{
sideLength = newValue / 3.0
}
}
override func simpleDescription() -> String {
println("An equilateral triagle with sides of length (sideLength).")
return "An equilateral triagle with sides of length (sideLength)." }
}
var triangle = EquilateralTriangle(sideLength: 3.1,name: "a triangle")
triangle.perimeter
triangle.perimeter = 9.9
注意:赋值器(setter)中,接收的值被自动命名为 newValue。 willSet 和 didSet 调用方法 class counter {
var count:Int = 0
func incrementBy(amount:Int,numberOfTimes times:Int){
count += amount * times
}
}
var count = counter()
count.incrementBy(2,numberOfTimes: 7)
注意 Swift 支持为方法参数取别名:在上面的代码里,numberOfTimes 面向外 部,times 面向内部。 ?的另一种用途 let optional:Square?=Square(sideLength: 2.3,name:"optional")
let sideLength = optional?.sideLength
println("sideLength = (sideLength)")
当 optionalSquare 为 nil 时,sideLength 属性调用会被忽略。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |