iosswiftcastingoption-typeforced-unwrapping

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


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?


Solution

  • 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.
            }
        }