Mostafa
Mostafa

Reputation: 1612

Converting from Int to String Swift 2.2

Dears

I have this case where chatId is a property of type Int

let StringMessage = String(self.listingChat?.messages.last?.chatId)

When I debug I find that StringMessage is returning Optional(15) Which means it is unwrapped. But at the same time XCode does not allow me to put any bangs (!) to unwrap it. So I am stuck with Unwrapped Variable. I know its noob question but it I really cant get it. Your help is appreciated.

Thank you

Upvotes: 0

Views: 367

Answers (3)

Jeffery Thomas
Jeffery Thomas

Reputation: 42598

It depends on what you want the default value to be.

Assuming you want the default value to be an empty string (""), You could create a function or a method to handle it.

func stringFromChatId(chatId: Int?) -> String {
    if let chatId = chatId {
        return String(chatId)
    } else {
        return ""
    }
}

let stringMessage = stringFromChatId(self.listingChat?.messages.last?.chatId)

Or you could handle it with a closure.

let stringMessage = { $0 != nil ? String($0!) : "" }(self.listingChat?.messages.last?.chatId)

If you don't mind crashing if self.listingChat?.messages.last?.chatId is nil, then you should be able to directly unwrap it.

let StringMessage = String((self.listingChat?.messages.last?.chatId)!)

or with a closure

let stringMessage = { String($0!) }(self.listingChat?.messages.last?.chatId)

Update

Assuming chatId is an Int and not an Optional<Int> (AKA Int?) I missed the most obvious unwrap answer. Sorry, I was tired last night.

let StringMessage = String(self.listingChat!.messages.last!.chatId)

Force unwrap all the optionals along the way.

Upvotes: 1

Carl Hung
Carl Hung

Reputation: 555

I think:

let StringMessage = String(self.listingChat?.messages.last?.chatId)!

Upvotes: 0

BallpointBen
BallpointBen

Reputation: 13934

Optionals have a very nice method called map (unrelated to map for Arrays) which returns nil if the variable is nil, otherwise it calls a function on the (non-nil) value. Combined with a guard-let, you get very concise code. (I've changed the case of stringMessage because variables should begin with a lower-case letter.)

guard let stringMessage = self.listingChat?.messages.last?.chatId.map { String($0) } else {
    // Do failure
}

// Success. stringMessage is of type String, not String?

Upvotes: 1

Related Questions