【问题标题】:Swift/SwiftUI property initializer error in struct结构中的 Swift/SwiftUI 属性初始化程序错误
【发布时间】:2021-10-11 00:27:54
【问题描述】:

我提供了一个非常基本的示例来总结我的问题

struct Greeting {

    var name = "Bob"
  
    var message = "Hi, " + name
}

var a = Test("John")
print(a.message)

我收到以下错误:

错误:不能在属性初始化器中使用实例成员“名称”;属性初始化程序在“self”可用之前运行

我已经尝试过初始化这些值,在惰性 vars 上创建我最好的猜测,并让 vars 计算值。任何帮助将不胜感激!

【问题讨论】:

  • 所有像print(a.message)这样的可执行代码都需要进入函数内部。除非你使用的是 Swift Playgrounds。
  • 您使用的是 SwiftUI 对吗?您可以将var a = Test("John"); print(a.message) 放入onAppear

标签: swift xcode debugging struct swiftui


【解决方案1】:

您在初始化结构之前使用name。如果您将消息设置为计算属性,它应该可以工作。

struct Greeting {
    var name = "Bob"

    var message: String {
        "Hi, " + name
    }
}

【讨论】:

  • 只是一个小错字(已经编辑和修复) - 你包括 = 所以不是计算属性。不会编译,但很好的答案!我认为这更好,因为如果name 发生变化(因为它是var),message also 在调用时会发生变化/具有正确的值,而接受的答案不会。跨度>
【解决方案2】:

你得到错误是因为在 Swift 中你需要给变量一些值才能使用它们。

   struct Greeting {
        var name = "Bob"      // <-- this variable is initialized with "Bob"
        var message: String   // <-- this var is not, you need to initialize it yourself
                             // which means you cannot use this before you give it a value
        
        // a very common approach is to have your own initializer function init.
        init(name: String, message: String) {
            self.name = name    // <-- this is initialized (again in our case)
            self.message = "Hi " + name  // this is now initialized the way you want it
        }

       // you can have many customized init, like this
       init() {
          // here because name is already initialized with Bob, it's ok
          self.message = "Hi " + name
       }
        
        // if you don't have a init function, swift creates a basic one (or more) for you
        // but it will not be the special one you wanted, like above.
    }

所以当 Greeting 创建时,首先调用 init 函数。那是您可以自定义创建问候语的地方。在此之前,您不能像在 "var message = "Hi, " + name" 中那样使用变量 "name"。

你可以这样使用它:

        let greet = Greeting()
        print(greet.message)

【讨论】:

    猜你喜欢
    • 2020-03-05
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    • 2020-10-16
    相关资源
    最近更新 更多