swiftclassinitializationswift4swift-class

Swift 4: How to initialise a class with values in one line?


I have a simple class in Swift 4 like this:

class Message {

    var messageBody : String = ""
    var sender : String = ""

}

And I want to (in one line) populate a variable with an instance of this object.

I tried to do it like this:

func retrieveMessages() {
    let messageDB = Database.database().reference().child("Messages")
    messageDB.observe(.childAdded) { (snapshot) in
        let snapshotValue = snapshot.value as! Dictionary<String,String>
        let text = snapshotValue["MessageBody"]!
        let sender = snapshotValue["Sender"]!
        let message = Message(messageBody: text, sender: sender) // relevant one liner
    }
}

But this does not work. What am I doing wrong?

Also note, that this:

let message = Message()
message.messageBody = text
message.sender = sender

works.


Solution

  • Just use a struct which provides a free memberwise initializer

    struct Message {   
    
        var messageBody : String 
        var sender : String
    }
    

    Or in case of a class write one

    class Message {
    
        var messageBody : String 
        var sender : String
    
        init(messageBody : String, sender : String) {
           self.messageBody = messageBody
           self.sender = sender
        }
    }
    

    In both cases there is no need to assign default values.

    For further information please read Swift Language Guide : Initialization