How can save the text of the label as an integer variable in swift?

1.9k views Asked by At

I need to save the changing text of my label as a variable, but if write the following code:

var warn = Int(self.dyn.text)

It says:

Value of optional type 'String?' must be unwrapped to a value of type 'String'
Coalesce using '??' to provide a default when the optional value contains 'nil'
Force-unwrap using '!' to abort execution if the optional value contains 'nil'

What code should I use?

3

There are 3 answers

1
Gustavo Vollbrecht On BEST ANSWER
var warn = Int(self.dyn.text ?? "") ?? 0

You have to provide a default value, just in case it's not possible to make the cast to Int. You also have to make sure the text value is not nil.

Take a look at optional chaining and optional binding

Another approach is:

    if let dynText = self.dyn.text {
        if let warn = Int(dynText) {

            // warn is an available int variable here.
        }
    }
3
pramod shukla On

2 way of doiing that

1: let warn = Int(self.dyn.text ?? "") ?? 0

2: let warn = Int(self.dyn.text!)!
7
Abdelahad Darwish On

Good. Because String can be "123" or "Hello,world" so it can be numeric or String text

When you use this Int(String) the initializer might fail, it returns an optional Int, rather than an Int

Example

let possibleNumber = "123"
let convertedNumber = Int(possibleNumber)
// convertedNumber is inferred to be of type "Int?", or "optional Int"

So you have to Unwrap it

Like that

   // unwrap text if TextField is not `!`  and then unwrap text when you convert to Int
    if let dynText = self.dyn.text , let warn = Int(dynText) {
       print(warn)
  }