Convert Input Data to Integer in 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
...

How do I convert a UITextField to an integer in Swift 2.0?

To convert the input string to an integer using Swift 2:

let guess:Int? = Int(input.text)

if guess == randomNumber {
// your code here
}

How to convert Swift 3 output of readLine() to Integer?

readLine() returns an Optional String.

To unwrap the String, you can use if let, and to convert the String to an integer, use Int().

Example:

import Foundation
if let typed = readLine() {
if let num = Int(typed) {
print(num)
}
}

Let's say you prompted the user twice:

let prompt1 = readLine()
let prompt2 = readLine()

Then:

if let response1 = prompt1, 
response2 = prompt2,
num1 = Int(response1),
num2 = Int(response2) {
print("The sum of \(num1) and \(num2) is \(num1 + num2)")
}

Get integer value from string in swift

Swift 2.0 you can initialize Integer using constructor

var stringNumber = "1234"
var numberFromString = Int(stringNumber)

Convert UITextField to Integer in Xcode 8 and Swift 3 and calculate with them

First of all, you need to create an IBAction for your button by dragging from Storyboard. I think it is not a problem.

//imagine this is your IBAction function on calculate click
@IBAction func calculate(_ sender: UIView) {
output.text = String(Int(input1.text!)! + Int(input2.text!)!)
}

I skipped all validations, but for the happy path it should work

convert user input to array of Ints in swift

You could use:

let text : String = "123a"
let digits = Array(text).map { String($0).toInt()! }
// Crash if any character is not int

But it will crash if input is not valid.

You can validate by checking the result of toInt():

let text : String = "1234"
var digits = Array(text).reduce([Int](), combine: { (var digits, optionalDigit) -> [Int] in
if let digit = String(optionalDigit).toInt() {
digits.append(digit)
}

return digits
})

if countElements(text) == digits.count {
// all digits valid
} else {
// has invalid digits
}


Related Topics



Leave a reply



Submit