0

I am new in swift anyone help me to understand

what is the purpose ? I should be used class label type !

is it possible to declare Computed property and Observers with class Label type ?

both ,either or neither ?

thank you

3

2 Answers 2

3

Type Properties can be created using either static or class keyword

  1. Computed properties can be created using class as well as static keyword.
  2. Property observers are not allowed using class keyword. They can only be used with static.

Example:

class First
{
    class var x : Int{
        return 3
    }

    static var y : Int{
        return 2
    }

//    error: class stored properties not supported in classes
//    class var z = 10 {
//        willSet{
//            print(newValue)
//        }
//    }

    static var w = 30 {
        willSet{
            print(newValue)
        }
    }
}
2
  • is it possible to Property observers without initialization?
    – user6847532
    Sep 21, 2016 at 13:51
  • 1
    Property observers can only be used with stored properties. So you need to initialize the property to some value before you start observing it for changes.
    – PGDev
    Sep 22, 2016 at 0:43
0

Class Computed Property

You can declare a class computed property

class Foo {
    class var p0: String { return "p0" }
}

Class Static Stored property

It is somehow possible but you need to use the static keyword

class Foo {
    static var p0: String = "p0" {
        didSet {
            print("Did set p0")
        }
    }
}
2
  • Stored property possible to without initialisation ?
    – user6847532
    Sep 21, 2016 at 3:20
  • 1
    Lazy stored properties can be created without initialization before the object is created. But still you have to give it some value/expression that can be computed when it is first used. For normal stored properties you need to initialize them either with default values or in init()
    – PGDev
    Sep 22, 2016 at 0:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.