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.
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.
Try this :
you need to create constant with static
static let screenSize = UIScreen.main.bounds.height
static let IS_IPHONE_4_OR_LESS = screenSize < 568.0
You can use this way to check which iPhone you are using :
struct ScreenSize{
static let width = UIScreen.main.bounds.size.width
static let height = UIScreen.main.bounds.size.height
static let maxLength = max(ScreenSize.width, ScreenSize.height)
static let minLength = min(ScreenSize.width, ScreenSize.height)
static let scale = UIScreen.main.scale
static let ratio1619 = (0.5625 * ScreenSize.width)
}
struct DeviceType{
static let isIphone4orLess = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.maxLength < 568.0
static let isIPhone5 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.maxLength == 568.0
static let isIPhone6 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.maxLength == 667.0
static let isIPhone6p = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.maxLength == 736.0
}
then use this as :
if DeviceType.isIPhone5 {
//Do iPhone 5 Stuff
}
You can not use any instance variable while initialising the property instead of that you should use below code.
class constant : NSObject {
let screenSize = UIScreen.main.bounds.height
var IS_IPHONE_4_OR_LESS = false
override init() {
IS_IPHONE_4_OR_LESS = screenSize < 568.0
}
}
Swift uses two-phase initialization for it's variables.
Class initialization in Swift is a two-phase process. In the first phase, each stored property is assigned an initial value by the class that introduced it. Once the initial state for every stored property has been determined, the second phase begins, and each class is given the opportunity to customize its stored properties further before the new instance is considered ready for use.
So you cannot access instance variables before you intitialize them. You can use a getter
for this variable Try using this
let screenSize = UIScreen.main.bounds.height
var IS_IPHONE_4_OR_LESS :Bool{
get{
return screenSize < 568.0
}
}
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
}
}