user190494 user190494 - 8 months ago 40
iOS Question

Trying to convert a hexadecimal text to a decimal in swift, but getting "Optional([num])" output

I am trying to convert a hexadecimal number to a decimal number. The user inputs a hexadecimal in a textview, on text edit action the decimal textview outputs the conversion. I am getting a strange behavior where the decimal textview is displaying "Optional[num]" IE "Optional(9) if I type in 9. Here is the hexadecimal text action listener:

@IBAction func inputHex(sender: AnyObject) {
if(Int(hexText.text!) != nil){
inputNumberText = hexText.text!

let st3 = Int(inputNumberText, radix: 16)
decText.text = String(st3)

let st3 = Int(inputNumberText, radix: 16)

calls the "failable initializer"

init?(_ text: String, radix radix: Int = default)

of struct Int, and that is failable for a good reason: It returns nil if the string is not a valid number representation in the given base. For example

Int("12XYZ", radix: 16)
Int("789", radix: 8)

would return nil. So st3 is an optional, and therefore String(st3) is the string "Optional(...)".

But note that there are more issues with your code:

  • Don't use AnyObject parameters in action methods. Always use the real type (in this case: UITextField) for better type checking. Xcode has an option for that when you connect the action.
  • Never unwrap forcefully. Use optional binding instead.
  • Comparing against nil can and should be avoided in almost all cases.

With regard to the last two points, compare When should I compare an optional value to nil?.

In your case

if (Int(hexText.text!) != nil)

is even wrong because it rejects valid hexadecimal strings like "ABCD".

This is how your action method could look like:

@IBAction func inputHex(sender: UITextField) {
    if let text = sender.text,
        let number = Int(text, radix: 16) {
        decText.text = String(number)

Both let text = ... and let number = ... are optional bindings in the context of the if-statement, and the if-block is only executed if both bindings succeed.