Convert entire string into integer and display it in textfield swift [duplicate] - swift

This question already has answers here:
Converting String to Int with Swift
(31 answers)
Closed 3 years ago.
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.

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")
}

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

Related

How to convert string to UInt32?

I am a beginner in swift and I am having a problem with convering string to UInt32.
let Generator = (ReadableJSON ["People"] [Person]["F1"].string! as NSString).doubleValue
if Generator == 1 {
NameLabel1 = ReadableJSON ["People"] [Person]["A1"].string as String!
NameImeNaObekt = ReadableJSON ["People"] [Person] ["B1"].string as String!
Picture = ReadableJSON ["People"] [Person] ["E1"].string as String!
} else {
let RGen = arc4random_uniform ("\(Generator)") // here is the error
}
Would you advise me how to fix it. The problem is in the last line, which is red and it says Cannot convert value of type String to UInt32.
The main idea is that I am reading the number from a JSON file and I have to populate this number into the arc4random_uniform.
arc4random_uniform(UInt32)
accept an UInt32 value but you are passing an String value to it
this converts your number to string
"\(Generator)"
the last line should be like this
let RGen = arc4random_uniform (UInt32(Generator))
and if you want to 'RGen' is an String you can do it this way
"\(RGen)"
String(RGen)
var RGen= 0
let RGen =int( arc4random_uniform ("\(Generator)") )
or
let RGen =( arc4random_uniform ("(Generator)") ).toInt
Look here

Swift 2.1 Binary operator * cannot be applied to two String operands

I have a calculator, but I can´t resolve this code:
#IBAction func calcular(sender: AnyObject) {
resultado.text = String(format: "", Sliderdosis)
let peso = pesoLabel.text
let dosis = dosisLabel.text
let total = (peso * dosis) * 5 / 250
/* in this point, the program write:
Binary operator * cannot be applied to two String operands** */
resultado.text = total
}
Some body help me please?
I´m a beginner, sorry!
The infix binary operator * does not exist for type String. You are attempting to multiply String objects (that are, inherently, not numerical) hence the error.
I'd suggest you make use of Leo Dabus excellent UITextField extension, however, in your case, extending UILabel (assuming pesoLabel and dosisLabel are UILabel instances)
extension UILabel {
var stringValue : String { return text ?? "" }
var integerValue: Int { return Int(stringValue) ?? 0 }
var doubleValue : Double { return Double(stringValue) ?? 0 }
var floatValue : Float { return Float(stringValue) ?? 0 }
}
Add this to the header of your .swift file. Thereafter you can update you button action method according to:
#IBAction func calcular(sender: AnyObject) {
resultado.text = String(format: "", Sliderdosis)
let peso = pesoLabel.doubleValue
let dosis = dosisLabel.doubleValue
let total = (peso * dosis) * 5 / 250
resultado.text = String(total)
}
Finally note that this subject is well-covered here on SO, so there exists existing threads that can help you convert string to numerical values. E.g.
Swift - Converting String to Int
Swift - How to convert String to Double
Also have a look at the Asking section here on SO, it contains lots of valuable information of how to ask, when to ask, and so on.

Converting String to Int in Swift

Hello I'm new to Swift and I'm building a calculator in Xcode. In my main storyboard I have a UIButton, UILabel and a UITextField that will get a number and by pressing the button, label's text should show the entered number + 5. In my app I need to convert a String variable to Int.
I tried the snippet below I didn't get any meaningful result.
var e = texti.text
let f: Int? = e.toInt()
let kashk = f * 2
label.text = "\(pashm)"
To make it clean and Swifty, I suggest this approach:
Swift 2 / 3
var string = "42" // here you would put your 'texti.text', assuming texti is for example UILabel
if let intVersion = Int(string) { // Swift 1.2: string.toInt()
let multiplied = 2 * intVersion
let multipliedString = "\(multiplied)"
// use the string as you wish, for example 'texti.text = multipliedString'
} else {
// handle the fact, that toInt() didn't yield an integer value
}
If you want to calculate with that new integer you have to unwrap it by putting an exclamation mark behind the variable name:
let stringnumber = "12"
let intnumber:Int? = Int(stringnumber)
print(intnumber!+3)
The result would be:
15
var string = "12"
var intVersion = string.toInt()
let intMultipied = intVersion! * 2
label.text= "\(intMultipied)"
Regarding how to convert a string to a integer:
var myString = "12" //Assign the value of your textfield
if let myInt = myString.toInt(){
//myInt is a integer with the value of "12"
} else {
//Do something, the text in the textfield is not a integer
}
The if let makes sure that your value can be casted to a integer.
.toInt() returns an optional Integer. If your string can be casted to a integer it will be, else it will return nil. The if let statement will only be casted if your string can be casted to a integer.
Since the new variable (constant to be exact) is a integer, you can make a new variable and add 5 to the value of your integer
var myString = "12" //Assign the value of your textfield
if let myInt = myString.toInt(){
//myInt is a integer with the value of “12”
let newInt = myInt + 5
myTextfield.text = "\(newInt)"
//The text of the textfield will be: "17" (12 + 5)
} else {
//Do something, the text in the textfield is not a integer
}

How to convert string in JSON to int Swift

self.event?["start"].string
The output is = Optional("1423269000000")
I want to get 1423269000000 as an Int
How can we achieve this? I have tried many ways such NSString (but it changed the value)
Your value: 1,423,269,000,000 is bigger than max Int32 value: 2,147,483,647. This may cause unexpected casting value. For more information, check this out: Numeric Types.
Try to run this code:
let maxIntegerValue = Int.max
println("Max integer value is: \(maxIntegerValue)")
In iPhone 4S simulator, the console output is:
Max integer value is: 2147483647
And iPhone 6 simulator, the console output is:
Max integer value is: 9223372036854775807
This information may help you.
But normally to convert Int to String:
let mInt : Int = 123
var mString = String(mInt)
And convert String to Int:
let mString : String = "123"
let mInt : Int? = mString.toInt()
if (mInt != null) {
// converted String to Int
}
Here is my safe way to do this using Optional Binding:
var json : [String:String];
json = ["key":"123"];
if var integerJson = json["key"]!.toInt(){
println("Integer conversion successful : \(integerJson)")
}
else{
println("Integer conversion failed")
}
Output:
Integer conversion successful :123
So this way one can be sure if the conversion was successful or not, using Optional Binding
I'm not sure about your question, but say you have a dictionary (Where it was JSON or not) You can do this:
var dict: [String : String]
dict = ["key1" : "123"]
var x : Int
x = dict["key1"].toInt()
println(x)
Just in case someone's still looking for an updated answer, here's the Swift 5+ version:
let jsonDict = ["key": "123"];
// Validation
guard let value = Int(jsonDict["key"]) else {
print("Error! Unexpected value.")
return
}
print("Integer conversion successful: \(value)")
// Prints "Integer conversion successful: 123"

How to convert Any to Int in Swift

I get an error when declaring i
var users = Array<Dictionary<String,Any>>()
users.append(["Name":"user1","Age":20])
var i:Int = Int(users[0]["Age"])
How to get the int value?
var i = users[0]["Age"] as Int
As GoZoner points out, if you don't know that the downcast will succeed, use:
var i = users[0]["Age"] as? Int
The result will be nil if it fails
Swift 4 answer :
if let str = users[0]["Age"] as? String, let i = Int(str) {
// do what you want with i
}
If you are sure the result is an Int then use:
var i = users[0]["Age"] as! Int
but if you are unsure and want a nil value if it is not an Int then use:
var i = users[0]["Age"] as? Int
“Use the optional form of the type cast operator (as?) when you are
not sure if the downcast will succeed. This form of the operator will
always return an optional value, and the value will be nil if the
downcast was not possible. This enables you to check for a successful
downcast.”
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks.
https://itun.es/us/jEUH0.l
This may have worked previously, but it's not the answer for Swift 3. Just to clarify, I don't have the answer for Swift 3, below is my testing using the above answer, and clearly it doesn't work.
My data comes from an NSDictionary
print("subvalue[multi] = \(subvalue["multi"]!)")
print("as Int = \(subvalue["multi"]! as? Int)")
if let multiString = subvalue["multi"] as? String {
print("as String = \(multiString)")
print("as Int = \(Int(multiString)!)")
}
The output generated is:
subvalue[multi] = 1
as Int = nil
Just to spell it out:
a) The original value is of type Any? and the value is: 1
b) Casting to Int results in nil
c) Casting to String results in nil (the print lines never execute)
EDIT
The answer is to use NSNumber
let num = subvalue["multi"] as? NSNumber
Then we can convert the number to an integer
let myint = num.intValue
if let id = json["productID"] as? String {
self.productID = Int32(id, radix: 10)!
}
This worked for me. json["productID"] is of type Any.
If it can be cast to a string, then convert it to an Integer.