How to fix the error (optional swift)?

About a week I started to learn swift and I came across an error which can't solve. Subject: optional data types. I'm more or less sorted out everything, but can't make unrapping String values?

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
March 19th 20 at 08:45
1 answer
March 19th 20 at 08:47
First you need to learn to make your own question and then look at this funny moment. If you entered the if block, then you already believe that your option string contains a value. That's just what makes you think that your gibberish in the string will be reduced to a number? Obviously it is not reduced it is not reduced. The expression Int(number2!) returns nil

Plus you'd have to start to read about the Optional binding.
Optional binding is much easier and more concise (I can assume that in combat mode programmers make unrapping with binding), but in the book need to make it forced. I have realized that number2 was originally not nil, this comes in an if and then an error occurs. Cannot yet understand how to make unrapping with forced in the case when the constant is of type String?... - robb_Luettge commented on March 19th 20 at 08:50
@robb_Luettge, understood like
if let fUnumber2 = Int(number2!) {
 sum = sum + fUnumber2
} else {
 print("number2 is nil")
}
- robb_Luettge commented on March 19th 20 at 08:53
@robb_Luettge, Yes that's right. If you still do the binding for the first if, will be generally cool. And nested checks can be combined into one. Here it is:
if let number2 = number2 {
 if let fUnumber2 = Int(number2) {
 // ...

if let number2 = number2, let fUnumber2 = Int(number2) {
 // ...
- Cecilia_Da commented on March 19th 20 at 08:56
var sum: Int = 0
let number2: String = "12asdasd"

if Int(number2) != nil {
sum = sum + Int(number2)!
print(sum)
} else {
print("number2 is nil")
} - helene commented on March 19th 20 at 08:59

Find more questions by tags Swift