Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert input field string to Int in Swift

Tags:

ios

swift

So im very new to making APP ad Swift, im trying to do some very simple input in text fields, take the value, and use them as Int's for some calculations.

But something is not working correct with the 'var distance'

        var handicapTal:Int
        var MagicNumber:Int
        var handicap = inputHCP.text.toInt()
        var distance = inputDistance.text.toInt()

        if (handicap >= 0 && handicap <= 20)
        {
            handicapTal = 30
        }
        else if(handicap > 20 && handicap <= 40){
            handicapTal = 10
        }

        MagicNumber = distance - handicapTal

Its the last line of code that give an error. It says Fatal error: Cant unwrap Optional.None

like image 279
Bidstrup Avatar asked Jun 15 '14 13:06

Bidstrup


People also ask

How to convert string value into integer in Swift?

Using Int initializer Swift provides the function of integer initializers using which we can convert a string into an Int type. To handle non-numeric strings, we can use nil coalescing using which the integer initializer returns an optional integer.

How do I cast an int in Swift?

To convert a float value to an Int, we can use the Int() constructor by passing a float value to it. Note: When we use this conversion the Integer is always rounded to the nearest downward value, like 12.752 to 12 or 6.99 to 6 .

What is textfield in Swift?

A control that displays an editable text interface.


1 Answers

distance, in your example, is an Int? otherwise known as an optional Int. .toInt() returns Int? since it is possible for the conversion from String to Int to fail. See the following example:

Welcome to Swift!  Type :help for assistance.
  1> let a = "12"
a: String = "12"
  2> let b = a.toInt()
b: Int? = 12
  3> let c = "Hello"
c: String = "Hello"
  4> let d = c.toInt()
d: Int? = nil
  5> if let e = a.toInt() { println("e = \(e)") }
e = 12
  6> if let f = c.toInt() { println("Huh?") }
  7> 
like image 58
Gryphon Avatar answered Sep 21 '22 07:09

Gryphon