SwiftyJD
SwiftyJD

Reputation: 5441

Cannot assign to value: 'message' is a 'let' constant in a fucntion

I'm trying to create a function that checks if a value is nil and if it is give it a default value. This is what I have so far:

func appendMessage(message: String?, fixLength: Int){
        if let message = message {
        } else {
             message = DEFAULT_CHAR//this is a default value, error is here
        }
          messageBody.append(getFixedLengthString(message, fixLength))
    }

Upvotes: 0

Views: 1611

Answers (2)

rmaddy
rmaddy

Reputation: 318824

You get the error for the obvious reason that the message parameter is a constant. Inside the else you are attempting to update the message parameter. The message variable created via the if let is also a constant but its scope is only inside the if, not the else nor after the whole if/else block. So the message variable you are attempting to use in the call to getFixedLengthString is the original message parameter.

The simplest solution is to use the ?? (nil-coalescing) operator:

func appendMessage(message: String?, fixLength: Int){
    messageBody.append(getFixedLengthString(message ?? DEFAULT_CHAR, fixLength))
}

The ?? operator returns the value on the left if it isn't nil and the value on the right if the left side is nil.

Upvotes: 5

Glenn Posadas
Glenn Posadas

Reputation: 13291

If you try to understand more of your logic/code, then you would solve it pretty easily.

This one should work.

func appendMessage(message: String?, fixLength: Int) {
    if let message = message {
        messageBody.append(getFixedLengthString(message, fixLength))
    } else {
         messageBody.append(getFixedLengthString(DEFAULT_CHAR, fixLength))
    }
}

Perhaps you can also try this one liner:

messageBody.append(getFixedLengthString(message == nil ? DEFAULT_CHAR : message!, fixLength))

Upvotes: 0

Related Questions