swift 初始化错误:self可用之前,无法在属性初始值设定项内使用示例成员[重复]

gojuced7  于 2023-05-21  发布在  Swift
关注(0)|答案(5)|浏览(149)

此问题已在此处有答案

How to initialize properties that depend on each other(4个答案)
6年前关闭。

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

“无法在self可用之前在属性初始值设定项中使用示例成员”,这是执行代码时遇到的错误。

9nvpjoqh

9nvpjoqh1#

初始化属性时不能使用任何示例变量,而不是使用下面的代码。

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
}
}
j8yoct9x

j8yoct9x2#

Swift对变量使用两阶段初始化。
Swift中的类初始化是一个两阶段的过程。在第一个阶段,每个存储的属性都由引入它的类赋予一个初始值。一旦确定了每个存储属性的初始状态,第二阶段就开始了,并且每个类都有机会在新示例被认为可以使用之前进一步定制其存储的属性。
所以在初始化示例变量之前不能访问它们。您可以使用getter作为该变量尝试使用

let screenSize = UIScreen.main.bounds.height
var IS_IPHONE_4_OR_LESS :Bool{
    get{
        return screenSize < 568.0
    }
}
qxsslcnc

qxsslcnc3#

试试这个:
您需要使用static创建常量

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

jm81lzqq4#

您可以使用此方法来检查您正在使用的iPhone:

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
}

然后使用这个作为:

if DeviceType.isIPhone5 {
    //Do iPhone 5 Stuff
}
ds97pgxw

ds97pgxw5#

常量指的是程序在执行过程中不能改变的固定值。IS_IPHONE_4_OR_LESS是一个常数,因此它需要在初始化类时的固定值,因此错误。在您的例子中,它是根据屏幕高度计算值,这样您就可以将其声明为如下所示的计算属性

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

相关问题