Swift学习笔记属性

struct FixedLengthRange {
    var firstValue: Int
    let length: Int
}
var rangeOfThreeItems = FixedLengthRange(firstValue: 0, length: 3)

rangeOfThreeItems.firstValue = 6


class DataImporter {
    var fileName = "data.txt"
}
class DataManager {
    lazy var importer = DataImporter()
    var data = [String]()
}

let manager = DataManager()
manager.data.append("Some Data")
manager.data.append("Some Data")


struct Point{
    var x = 0.0, y = 0.0
}
struct Size {
    var width = 0.0, height = 0.0
}
struct Rect {
    var origin = Point()
    var size = Size()
    var center: Point{
        get{
            let  centerX = origin.x + (size.width / 2)
            let  centerY = origin.y + (size.height / 2)
            return Point(x: centerX, y: centerY)
        }
        set(newCenter)
        {
            origin.x = newCenter.x - (size.width / 2)
            origin.y = newCenter.y - (size.height / 2)
        }
    }
}
var square = Rect(origin: Point(x: 0.0, y: 0.0), size: Size(width: 10.0, height: 10.0))

let initialSquareCenter = square.center
square.center = Point(x: 15.0, y: 15.0)

struct Cuboid {
    var width = 0.0
    var volume: Double {
        return width
    }
}

class StepCounter {
    var totalSteps: Int = 0 {
        willSet(newTotalSteps) {
            println(newTotalSteps)
        }
        didSet{
            if(totalSteps > oldValue )
            {
                println(totalSteps - oldValue)
            }
        }
    }
}

let stepCounter = StepCounter()
stepCounter.totalSteps = 200

class SomeClass {
    static var i = 100
    class var computedTypeProperty: Int {
        get{
            return 100
        }
    }
}

以上是属性的基本用法,与其他语言类似,但是关于静态属性却有一点不同的定义,在定义类的静态属性的时候

必须加入class关键字

属性有get,set方法

也可以使用didSet与willSet进行监控属性的值。

你可能感兴趣的:(swift)