Swift属性
3335 ワード
ストレージ属性と計算属性
OC
struct Person2 {
var name: String
var age : Int
let card: String //
}
var p2 = Person2(name: "HaRi", age: 24, card: "1234")
p2.name = "helloName"
p2.age = 25
//
//p2.card = "333" Error!
getterと
setterを1つ提供することによって、他のプロパティと値を間接的に取得し、設定します.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))
square.center = Point(x: 15.0, y: 15.0)
class Calcuator {
var a:Int = 1
var b:Int = 1
var sum:Int{
get{
return a + b
}
set{ // ,newValue
b = newValue - a
}
}
}
class Calcuator2 {
var a:Int = 1
var b:Int = 1
var sum:Int {
return a + b
}
}
Swiftのlazy
lazy var stutentList : Array = {
var arrrM:Array = []
return arrrM as [AnyObject]
}()
属性オブザーバ
class Line3{
var start: Double = 0.0{
willSet{
print("willSet newValue = \(newValue)")
}
didSet{
print("didSet newValue = \(start) ,oldValue = \(oldValue)")
}
}
var end: Double = 0.0
}
var l = Line3()
l.start = 10.0
以上の印刷出力
willSet newValue = 10.0
didSet oldValue = 0.0