Search code examples
swiftvariables

Initialization error: Cannot use instance member within property initializer before self is available


let screenSize = UIScreen.main.bounds.height
let IS_IPHONE_4_OR_LESS  = screenSize < 568.0

"Cannot use instance member within property initializer before self is available" this is the error am getting when executing the code.


Solution

  • Constants refer to fixed values that a program may not alter during its execution. IS_IPHONE_4_OR_LESS is a constant hence it need the fix value at the time of initialisation of a class hence the error. In your case its computing the value based on the screen height so you can declare it as a computed property like below

     class Constants: NSObject {
        let screenSize = UIScreen.main.bounds.size.height
        var IS_IPHONE_4_OR_LESS: Bool {
            return screenSize < 568
        }
     }