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.

2
  • You have to add ! . see my code var newSTrings = Int(result!)! . you have to enter only numeric value into textfield. Commented Mar 19, 2019 at 5:05
  • 1
    Got your point!Thanks for the help! Commented Mar 19, 2019 at 5:51

2 Answers 2

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")
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.