Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active May 1, 2016 04:13
Show Gist options
  • Save KentarouKanno/3a042e26b4a9c40e01ed to your computer and use it in GitHub Desktop.
Save KentarouKanno/3a042e26b4a9c40e01ed to your computer and use it in GitHub Desktop.
Propertyies

Property

★ Stored Propertyies

// Lazy Stored Propertyies
lazy var lazyProperty: String = ""

// Property Observers
class Person {
    var age: Int = 0 {
        willSet { print("willSet: \(age) -> \(newValue)") }
        didSet  { print("didSet : \(oldValue) -> \(age)") }
    }
}

let p = Person()
p.age = 20


// 使用する変数名を自分で設定する場合

class Person1 {
    var age: Int = 0 {
        willSet(newAge) { print("willSet: \(age) -> \(newAge)") }
        didSet(oldAge)  { print("didSet : \(oldAge) -> \(age)") }
    }
}

★ Computed Propertyies

var firstName: String = "Kentarou"
var lastName : String = "Kanno"

var fullName: String {
    get  {
        return firstName + " " + lastName
    }
    set(newValue) {
        let nameArray = newValue.componentsSeparatedByString(" ")
        firstName = nameArray[0]
        lastName  = nameArray[1]
    }
}

// Read-Only Computed Propertyies
var isAdult: Bool {
    return (age >= 20)
}

// Type Propertyies
static var typePropertyies: String = ""

//=> ClassName.typePropertyies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment