Converting String to Int in Swift - 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
}

Related

Swift get decimal value for String characters

Is it possible to get the decimal value for String characters in Swift?
something like:
let words:String = "1 ring to rule them all"
var value:Int = 0
for i in 0..<words.count {
let char = words[words.index(words.startIndex,offsetBy:i)]
value += Int(char.decimal)
}
where the first character in "1 ring to rule them all" is 49. Possible?
you could try this:
let words = "1 ring to rule them all"
var value: Int = 0
for i in 0..<words.count {
let char = words[words.index(words.startIndex,offsetBy:i)]
if let val = char.asciiValue {
print("----> char: \(char) val: \(val)") // char and its "decimal" value
value += Int(val)
}
}
print("\n----> value: \(value) \n") // meaningless total value
ok, looks like this is the way:
let characterString = "蜇"
let scalars = characterString.unicodeScalars
let ui32:UInt32 = scalars[scalars.startIndex].value
If you want to add up the Unicode values associated with a string, it would be:
var value = 0
for character in string {
for scalar in character.unicodeScalars {
value += Int(scalar.value)
}
}
Or, alternatively:
let value = string
.flatMap { $0.unicodeScalars }
.compactMap { $0.value }
.reduce(0, +)
While the above adds the values, as requested, if you are trying to get a numeric representation for a string, you might consider using hashValue, or checksum, or CRC, or the like. Simply summing the values will not be able to detect, for example, character transpositions. It just depends upon your use-case for this numeric representation of your string.

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

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

Swift String to Int Always Returns nil

I am trying to convert a String to an Int. Seems simple enough, but for somer reason it is always returning nil.
I'm just writing a simple extension to convert dollars to cents:
func dollarsToCents() -> Int {
var temp = self;
temp = temp.replacingOccurrences(of: "$", with: "")
temp = temp.replacingOccurrences(of: ",", with: "")
if let number = Int(temp) {
return number*100
}
return 0
}
I have temp set to "$250.89". number is always nil. No matter how I approach converting temp to an Int it is always nil. Anyone know what I'm doing wrong?
Problem is, that string "250.89" (after removing currency symbol) can't be converted to Int because 250.89 isn't integer. So fix your code by converting it to Double
func dollarsToCents() -> Int {
var temp = self
temp.removeAll { "$,".contains($0) }
//temp = temp.replacingOccurrences(of: "[$,]", with: "", options: .regularExpression)
return Int(((Double(temp) ?? 0) * 100).rounded())
}
or if your "number" always have two decimal places
func dollarsToCents() -> Int {
var temp = self
temp.removeAll { !("0"..."9" ~= $0) }
return Int(temp) ?? 0
}
But I think solution is much easier. Your goal should be saving price value as number (Double,...). Then you don't have to convert String to Double and you can just multiply your number. Then when you need to add currency symbol, just convert your value to String and add $ or use NumberFormatter
let price = 250.89
let formattedPrice = "$\(price)" // $250.89
let price = 250.89
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.currencyCode = "USD"
let formattedPrice = formatter.string(from: price as NSNumber)! // $250.89
Just adding this for the bizarre edge-case that I just encountered - be sure there aren't any whitespaces either trailing or leading in your string when converting to Int from String.
Eg.
for date in next_thirty_days {
let date_buffer: String = date.description[8...9]
date_list.append(Int(date_buffer)!)
}
This will fail if the value for date_buffer has a leading or trailing white-space.
Another edge-case is that there's a leading 0 in the string variable, eg. 07.
Hope it helps :)

String convert to Int and replace comma to Plus sign

Using Swift, I'm trying to take a list of numbers input in a text view in an app and create a sum of this list by extracting each number for a grade calculator. Also the amount of values put in by the user changes each time. An example is shown below:
String of: 98,99,97,96...
Trying to get: 98+99+97+96...
Please Help!
Thanks
Use components(separatedBy:) to break up the comma-separated string.
Use trimmingCharacters(in:) to remove spaces before and after each element
Use Int() to convert each element into an integer.
Use compactMap (previously called flatMap) to remove any items that couldn't be converted to Int.
Use reduce to sum up the array of Int.
let input = " 98 ,99 , 97, 96 "
let values = input.components(separatedBy: ",").compactMap { Int($0.trimmingCharacters(in: .whitespaces)) }
let sum = values.reduce(0, +)
print(sum) // 390
For Swift 3 and Swift 4.
Simple way: Hard coded. Only useful if you know the exact amount of integers coming up, wanting to get calculated and printed/used further on.
let string98: String = "98"
let string99: String = "99"
let string100: String = "100"
let string101: String = "101"
let int98: Int = Int(string98)!
let int99: Int = Int(string99)!
let int100: Int = Int(string100)!
let int101: Int = Int(string101)!
// optional chaining (if or guard) instead of "!" recommended. therefore option b is better
let finalInt: Int = int98 + int99 + int100 + int101
print(finalInt) // prints Optional(398) (optional)
Fancy way as a function: Generic way. Here you can put as many strings in as you need in the end. You could, for example, gather all the strings first and then use the array to have them calculated.
func getCalculatedIntegerFrom(strings: [String]) -> Int {
var result = Int()
for element in strings {
guard let int = Int(element) else {
break // or return nil
// break instead of return, returns Integer of all
// the values it was able to turn into Integer
// so even if there is a String f.e. "123S", it would
// still return an Integer instead of nil
// if you want to use return, you have to set "-> Int?" as optional
}
result = result + int
}
return result
}
let arrayOfStrings = ["98", "99", "100", "101"]
let result = getCalculatedIntegerFrom(strings: arrayOfStrings)
print(result) // prints 398 (non-optional)
let myString = "556"
let myInt = Int(myString)

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.