使用Swift将String转换为Int

这篇博客讨论了如何在Swift中将文本框中的字符串值转换为整数,以便进行数学计算。在Swift的不同版本中,转换方法有所变化,包括使用integer's constructor、NSString、Int.init(string:)以及考虑使用DecimalPad键盘类型来限制输入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文翻译自:Converting String to Int with Swift

The application basically calculates acceleration by inputting Initial and final velocity and time and then use a formula to calculate acceleration. 该应用程序基本上通过输入初始和最终速度和时间来计算加速度,然后使用公式来计算加速度。 However, since the values in the text boxes are string, I am unable to convert them to integers. 但是,由于文本框中的值是字符串,我无法将它们转换为整数。

@IBOutlet var txtBox1 : UITextField
@IBOutlet var txtBox2 : UITextField
@IBOutlet var txtBox3 : UITextField
@IBOutlet var lblAnswer : UILabel


@IBAction func btn1(sender : AnyObject) {

    let answer1 = "The acceleration is"
    var answer2 = txtBox1
    var answer3 = txtBox2
    var answer4 = txtBox3

#1楼

参考:https://stackoom.com/question/1dBRt/使用Swift将String转换为Int


#2楼

myString.toInt() - convert the string value into int . myString.toInt() - 将字符串值转换为int。

Swift 3.x Swift 3.x

If you have an integer hiding inside a string, you can convertby using the integer's constructor, like this: 如果你有一个隐藏在字符串中的整数,你可以使用整数的构造函数进行转换,如下所示:

let myInt = Int(textField.text)

As with other data types (Float and Double) you can also convert by using NSString: 与其他数据类型(Float和Double)一样,您也可以使用NSString进行转换:

let myString = "556"
let myInt = (myString as NSString).integerValue

#3楼

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): 基本的想法, 请注意,这仅适用于Swift 1.x (查看ParaSara的答案 ,了解它在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 Swift 4的更新

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

#4楼

Use this: 用这个:

// get the values from text boxes
    let a:Double = firstText.text.bridgeToObjectiveC().doubleValue
    let b:Double = secondText.text.bridgeToObjectiveC().doubleValue

//  we checking against 0.0, because above function return 0.0 if it gets failed to convert
    if (a != 0.0) && (b != 0.0) {
        var ans = a + b
        answerLabel.text = "Answer is \(ans)"
    } else {
        answerLabel.text = "Input values are not numberic"
    }

OR 要么

Make your UITextField KeyboardType as DecimalTab from your XIB or storyboard, and remove any if condition for doing any calculation, ie. 从您的XIB或故事板中将您的UITextField KeyboardType设置为DecimalTab,并删除任何if条件以进行任何计算,即。

var ans = a + b
answerLabel.text = "Answer is \(ans)"

Because keyboard type is DecimalPad there is no chance to enter other 0-9 or . 因为键盘类型是DecimalPad,所以没有机会输入其他0-9或。

Hope this help !! 希望这有帮助!!


#5楼

You wanna use NSNumberFormatter().numberFromString(yourNumberString) . 你想使用NSNumberFormatter().numberFromString(yourNumberString) It's great because it returns an an optional that you can then test with an "if let" to determine if the conversion was successful. 它很棒,因为它返回一个可选项,然后您可以使用“if let”进行测试,以确定转换是否成功。 eg. 例如。

     var myString = "\(10)"
     if let myNumber = NSNumberFormatter().numberFromString(myString) {
          var myInt = myNumber.integerValue
          // do what you need to do with myInt
     } else {
          // what ever error code you need to write
     }

#6楼

Update Answer for swift 2.0 : 更新swift 2.0的答案

toInt() method is given a error. toInt()方法给出了错误。 Because,In Swift 2.x, the .toInt() function was removed from String. 因为,在Swift 2.x中, .toInt()函数已从String中删除。 In replacement, Int now has an initializer that accepts a String: 在替换中,Int现在有一个接受String的初始化器:

let a:Int? = Int(firstText.text)     // firstText is UITextField  
let b:Int? = Int(secondText.text)   // secondText is UITextField
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值