SagittariusA
SagittariusA

Reputation: 5427

Swift: how to convert Optional("Optional(str)") to Int

In my Swift class I have the following:

var detailItem: Task?
var cellData:[String:String] = [:]

/* prepareForSegue not called before */
if (detailItem == nil) {
        self.cellData = ["id":"", "titolo":"", "oggetto":"", "check_mail":"", "progetto_nome":"", "assegnato_a":"", "richiesto_da":"", "priorita":"", "termine_consegna":"", "stato":"Aperto"]
    }

/* prepare for segue has been called */
else {
        self.cellData["id"] = String(stringInterpolationSegment: self.detailItem!.id)
        self.cellData["titolo"] = self.detailItem!.titolo
        self.cellData["oggetto"] = self.detailItem!.oggetto

        if (self.detailItem!.check_mail) {
            self.cellData["check_mail"] = "true"
        }
        else {
            self.cellData["check_mail"] = "false"
        }

        self.cellData["progetto_nome"] = self.detailItem!.progetto_nome
        self.cellData["assegnato_a"] = self.detailItem!.assegnato_a
        self.cellData["richiesto_da"] = self.detailItem!.richiesto_da
        self.cellData["priorita"] = self.detailItem!.priorita

        self.dateFormatter.dateFormat = "yyyy-MM-dd"
        self.cellData["termine_consegna"] = self.dateFormatter.stringFromDate(self.detailItem!.termine_consegna)

        self.cellData["stato"] = self.detailItem!.stato

        var editButton:UIBarButtonItem = UIBarButtonItem(title: "Modifica", style: UIBarButtonItemStyle.Plain, target: self, action: "switchMode:")
        self.navigationItem.rightBarButtonItem = editButton
    }

where some properties of the Task class are optionals (like the id) and so they may be nil. When I need to perform a task update operation I need to retrieve the data from cellData, create a task object and use it to update the database which requires an id. So this is what I do:

var taskToUpdate = Task(id: self.cellData["id"]!.toInt(),
                        ...)

The problem is that id is always set to nil. I have tried:

println(self.cellData["id"]!.toInt())

and what I get is this:

Optional("Optional(102)").

Which is the correct way to cast that into Int?

Upvotes: 0

Views: 1029

Answers (2)

Sulthan
Sulthan

Reputation: 130172

You have two problems there:

  1. .toInt() returns an optional.
  2. The id in self.detailItem!.id is probably an optional, too.

The result is that an optional id with value 102 is converted to "Optional(102)" and not "102" as you would expect.

I would advise you a simple solution - don't use dictionaries to hold your data, use objects where properties have the correct types. Don't go around converting your numbers to strings and back. Otherwise you will have to put force unwraps everywhere, e.g.:

String(stringInterpolationSegment: self.detailItem!.id!)

Upvotes: 1

vadian
vadian

Reputation: 285250

The function toInt() returns always an optional because there are only a few cases where strings can be converted to integers. If you can ensure that the value is never nil, unwrap it

println(self.cellData["id"]!.toInt()!)

otherwise use optional bindings

If let idInt = self.cellData["id"]!.toInt() { println(idInt) }

Upvotes: 1

Related Questions