0

I want to load form_Mesaj1 in the text data, but I get this error in the form_Mesaj1 line. What is the problem?

import Foundation

public struct Message {
    var text:String
    let isIncoming:Bool
    let date:Date
}


class MessageViewController: ChatVCWithTableView {
  let form_Mesaj1 = String()
   private let messages = [
        [
            Message(text:"\(form_Mesaj1)", isIncoming:true, date: Date.dateFromCustomString(dateString: "12/22/2018"))
        ]
  • 1
    It's like the error message say, you can't use form_Mesaj1 in this scope. Initialize `messages` in an `init()` instead (Or use an empty string instead since that is what form_Mesaj1 is). – Joakim Danielson Dec 19 '19 at 10:07

1 Answers1

0

The compiler con not be sure that form_Mesaj1 is going to initialize before messages. It can be sure of that only after self (all stored properties) has been initialized.

Lazy way:

So you can make it lazy:

private lazy var messages =  [
    Message(text:"\(form_Mesaj1)", isIncoming: true, date: Date.dateFromCustomString(dateString: "12/22/2018"))
]

This way the compiler can be sure that the form_Mesaj1 is initialized before using it, because you must call messages on an existing ('aka' initialized) object, right?!


More stricted way:

Also up can initialize them manually:

class MessageViewController: ChatVCWithTableView {
    let form_Mesaj1: String
    private let messages: [Message]

    init(form_Mesaj1: String) {
        self.form_Mesaj1 = form_Mesaj1
        messages = [
            Message(text:"\(form_Mesaj1)", isIncoming: true, date: Date.dateFromCustomString(dateString: "12/22/2018"))
        ]
    }
}
Community
  • 1
  • 1
Mojtaba Hosseini
  • 95,414
  • 31
  • 268
  • 278