A
A
Alex Bro2019-03-27 08:52:03
Swift
Alex Bro, 2019-03-27 08:52:03

How to fix the error (optional swift)?

About a week ago I started learning swift and came across a bug that I can't solve. Topic: optional data types. In general, I more or less figured out everything to everyone, but I can’t do the unraping of the String value?
Conditions:

let number2 :  String? = "78hyf9"

if number2 != nil {
    sum = sum + Int(number2!)!
} else {
    print("number2 is nil")
}

Error
error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
Fatal error: Unexpectedly found nil while unwrapping an Optional value

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
doublench21, 2019-03-27
@doublench21

First you need to learn how to formulate your question, and only then look at such a funny moment. If you've entered the if block, then you're already sure that your optional string contains a value. That's just where did you get the idea that your krakozyabra in the line will be reduced to a number? Obviously it will not come down and it will not come down. The expression Int(number2!) returns nil
Plus, you should be reading about Optional Binding already.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question