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
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.
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 .
A control that displays an editable text interface.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With