ios - How to access class constants and variables -


why can not perform operations variable or constant @ class level? not allowed or there keyword need use access them? bad practice?

controller:

class viewcontroller: uiviewcontroller {     let 1 = 1     let 2 = 2     var sum = 1 + 2 } 

error:

viewcontroller.type not have member named 'one'

class variables , constants must static, e.g., static let 1 = 1.

here suffices 2 let constants static them usable in initializing both class , instance variables. following works me:

class myclass {     static let 1 = 1     static let 2 = 2     static var sum = 1 + 2     var instanceproduct = 1 * 2 }  myclass.one myclass.sum myclass().instanceproduct 

note in above example can myclass.sum = 5. if meant sum constant well, change static let sum = 1 + two.

the requirement constants use outside of functions , closures declared static let. implication of constant entire class. if need instance-specific constants, cannot use them outside of functions or closures (as you've noticed) – workaround variable sum suggest lazy variable initialized closure:

class myclass {     let one: int // value given in `init`     let 2 = 2     lazy var sum: int = { self.one + self.two }()      init(one: int = 1) {         self.one = 1     } } myclass().sum // 3 myclass(one: 2).sum // 4 

Comments

Popular posts from this blog

java - Andrioid studio start fail: Fatal error initializing 'null' -

android - Gradle sync Error:Configuration with name 'default' not found -

StringGrid issue in Delphi XE8 firemonkey mobile app -