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.