0

I want to develop an application that can convert UITextField values into integer, float and double. I am facing problem to convert String value into Integer. Can anyone suggest the better way for conversion. I have tried the following code but it didn't worked for Swift 4 and Xcode 10.

let result = txtTotakeInput.text    
var newSTrings = Int(result!)

Thanks in advance.

Rocky
  • 2,673
  • 1
  • 20
  • 24

2 Answers2

1

A better and safer way to handle all three types Int, Float and Double will be

let result = txtTotakeInput.text   
if let intVal = Int(result ?? "") {
    // Use interger
}
else if let floatVal = Float(result ?? "") {
    // Use float
}
else if let doubleVal = Double(result ?? "") {
    // Use double
}
else {
    print("User has not entered integer, float or double")
}
Sunil Sharma
  • 2,586
  • 1
  • 22
  • 34
0

Int.init(_ string) returns an optional, since its possible that the string is not an integer. So you can either make newStrings optional like var newSTrings = result.flatMap(Int.init) or nil coalesce it to zero or some other default var newSTrings = result.flatMap(Int.init) ?? 0

Josh Homann
  • 15,266
  • 3
  • 28
  • 33