Converting String to Int With Swift

Converting String to Int with Swift

Basic Idea, note that this only works in Swift 1.x (check out ParaSara's answer to see how it works in Swift 2.x):

    // toInt returns optional that's why we used a:Int?
let a:Int? = firstText.text.toInt() // firstText is UITextField
let b:Int? = secondText.text.toInt() // secondText is UITextField

// check a and b before unwrapping using !
if a && b {
var ans = a! + b!
answerLabel.text = "Answer is \(ans)" // answerLabel ie UILabel
} else {
answerLabel.text = "Input values are not numeric"
}

Update for Swift 4

...
let a:Int? = Int(firstText.text) // firstText is UITextField
let b:Int? = Int(secondText.text) // secondText is UITextField
...

Converting from string to int in Swift

A text field contains a string (in its text property); it is not itself a string. And since that string can change, you should ask the text field for it each time you need it.

You can use a guard let statement to unwrap all of the optionals (since each text field's text is optional, and the Int conversion also returns optional), like this:

class ViewController {
@IBOutlet weak var firstNumber: UITextField!
@IBOutlet weak var secondNumber: UITextField!
@IBOutlet weak var total: UILabel!
@IBOutlet weak var segmentedControlCalculate: UISegmentedControl!

@IBAction func segmentedControlAddSubtract(sender: AnyObject) {
switch segmentedControlCalculate.selectedSegmentIndex {
case 0:
operation = (+)
case 1:
operation = (-)
default:
return
}
updateTotalLabel()
}

private var operation: ((Int, Int) -> Int)?

private func updateTotalLabel() {
guard let operation = operation,
firstString = firstNumber.text,
firstInput = Int(firstString),
secondString = secondNumber.text,
secondInput = Int(secondString)
else {
total.text = "Bogus input"
return
}
let result = operation(firstInput, secondInput)
total.text = "Total = \(result)"
}
}

How to convert String to Int in Swift?

String to Int conversion is not complicated. You simply do the conversion at the wrong place. You are trying to reference one member in the initialization of another member, that is not allowed. In this particular case simply because fldTotalUnits has the value nil when you would try to use it via Int(fldTotalUnits). When creating an instance of your class ViewController fldTotalUnits is set to nil and initialized with a useful value later. Therefore what you have to do in the first place is move the line into a separate method:

func doSomething() {
var intTotalUnits:Int? = Int(fldTotalUnits)
}

Now you will see that the compiler complains about there not being a suitable initializer because you have to access the text property of fldTotalUnits instead of using the actual textfield:

func doSomething() {
var intTotalUnits:Int? = Int(fldTotalUnits.text!)
}

Now you can think about moving the declaration of intTotalUnits to somewhere else, but setting its value has to happen in some method.

How to convert a String to an Int in Swift?

Use the prefix function on the characters array

let startString = "20932121133222"
let prefix = String(startString.characters.prefix(2))
let num = Int(prefix)

Prefix allows you to get the first n elements from the start of an array, so you get these, convert them back to a String and then convert the resulting String to an Int

How to convert string to Int? Swift

String to int returns optional. For example:

let myInt2 = Int(myString) ?? 0

For you example it will be:

let spentBudgetInt = Int(spentBudget) ?? 0

Converting String to Int in Swift

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
}

How can I convert a string in a textfield to an Int in Swift?

At first glance, it looks like you have two things to check for:

  • is AnzahlString.text present, and
  • does it represent an Int

The first check is in fact not necessary, since .text will never return nil, even though it's marked as Optional. This means you can safely force-unwrap it.

The second check is easily done by using the ?? operator:

let AnzahlAInt = Int(AnzahlString.text!) ?? 0

PS, just as a stylistic hint: variable names in Swift ususally start with a lowercase letter, names starting with capital letters are used for types.

PPS: your code as written shadows AnzahlAInt - the value of your var is never changed.

How to convert 'String.Element' to 'Int'?

What's the issue in sum += i, as the error said, i is a Character, and sum a Int.

Can you make addition between bananas & apples? It's the same logic here.

So you might want to have its Int equivalent with Int(i)

It's returning an optional value, because there is no guarantee that i is valid. You check isNumber before hand, but the line itself doesn't know that. So you can soft unwrap, or if you are sure force unwrap:

sum += Int(String(i))! //Char -> String -> Int

Because there is a String.init(someChar), and Int.init(someString), but not Int.init(someChar), that's why there is the double init().

BUT, keeping your logic, you are iterating characters per characters...
So, in the end you have:

1 + 2 + 3 + 0 + 6 + 7 (ie 19), not 1 + 2 + 30 + 67 (ie 100) as expected.

So if you want to iterate, you need to "group" the consecutive numbers...

With basic for loops, your can do this (it's a possible solution, might no be the better one, but a working one)

let numsInStr = "1abc2x30yz67"

var lastWasNumber = false
var intStrings: [String] = []

for aCharacter in numsInStr {
if aCharacter.isNumber {
if !lastWasNumber {
intStrings.append(String(aCharacter))
} else {
intStrings[intStrings.count - 1] = intStrings[intStrings.count - 1] + String(aCharacter)
}
lastWasNumber = true
} else {
lastWasNumber = false
}
print("After processing: \(aCharacter) - got: \(intStrings)")
}

print(intStrings)

var sum = 0
for anIntString in intStrings {
sum += Int(anIntString)!
}
print("Sum: \(sum)")

At your level, never hesitate to add print() (but never just the variable, always add an additional text which will be context to know from where it's called).

The output being:

$>After processing: 1 - got: ["1"]
$>After processing: a - got: ["1"]
$>After processing: b - got: ["1"]
$>After processing: c - got: ["1"]
$>After processing: 2 - got: ["1", "2"]
$>After processing: x - got: ["1", "2"]
$>After processing: 3 - got: ["1", "2", "3"]
$>After processing: 0 - got: ["1", "2", "30"]
$>After processing: y - got: ["1", "2", "30"]
$>After processing: z - got: ["1", "2", "30"]
$>After processing: 6 - got: ["1", "2", "30", "6"]
$>After processing: 7 - got: ["1", "2", "30", "67"]
$>["1", "2", "30", "67"]
$>100

We rely on Int(someString) (and force unwrapping), but sum += Int(anIntString) ?? 0 should be safer. Since for too big values, if you have "a1234567890123456789123456789123456789" for instance, I'm not sure that Int will be big enough to handle that value. That some edges cases that you need to be aware of.

With high level methods, you can use componentsSeparated(by:) to get an array of only string & only letters. Then, you can filter() (if needed), or compactMap() and transform to Int if possible, then sum (with reduce(into:_:).

As suggested, another solution without keeping a list of String could be:

var sum = 0
var lastWasNumber = false
var currentIntString = ""

for aCharacter in numsInStr {
if aCharacter.isNumber {
if !lastWasNumber {
sum += Int(currentIntString) ?? 0
currentIntString = "" // Reset, but in fact since we override with the next line, it's not necessary to write it
currentIntString = String(aCharacter)
} else {
currentIntString += String(aCharacter)
}
lastWasNumber = true
} else {
lastWasNumber = false
}
print("After processing: \(aCharacter) - got: \(currentIntString) - current sum: \(sum)")
}

sum += Int(currentIntString) ?? 0

print("Sum: \(sum)")

Here, we keep currentInString as a "buffer".

This could be simplified too by removing lastWasNumber and checking instead currentIntString:

var sum = 0
var currentIntString = ""

for aCharacter in numsInStr {
if aCharacter.isNumber {
if currentIntString.isEmpty {
currentIntString = String(aCharacter)
} else {
currentIntString += String(aCharacter)
}
} else {
sum += Int(currentIntString) ?? 0
currentIntString = ""
}
print("After processing: \(aCharacter) - got: \(currentIntString) - current sum: \(sum)")
}

sum += Int(currentIntString) ?? 0

print("Sum: \(sum)")

Convert entire string into integer and display it in textfield swift

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


Related Topics



Leave a reply



Submit