ios 使用 Swift 将 String 转换为 Int

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24115141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:42:49  来源:igfitidea点击:

Converting String to Int with Swift

iosswiftintuitextfield

提问by Marwan Qasem

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

采纳答案by Narendar Singh Saini

Basic Idea, note that this only works in Swift 1.x(check out ParaSara's answerto 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
...

回答by Paraneetharan Saravanaperumal

Update Answer for swift 2.0:

更新 swift 2.0 的答案

toInt()method is given a error. Because,In Swift 2.x, the .toInt()function was removed from String. In replacement, Int now has an initializer that accepts a String:

toInt()方法报错。因为,在 Swift 2.x 中,该.toInt()函数已从 String 中移除。作为替代,Int 现在有一个接受字符串的初始化器:

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

回答by Kumar KL

myString.toInt()- convert the string value into int .

myString.toInt()- 将字符串值转换为 int 。

Swift 3.x

斯威夫特 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

回答by Leo Dabus

edit/update: Xcode 11.4 ? Swift 5.2

编辑/更新:Xcode 11.4?斯威夫特 5.2

Please check the comments through the code

请通过代码查看评论



IntegerField.swiftfile contents:

IntegerField.swift文件内容:

import UIKit

class IntegerField: UITextField {

    // returns the textfield contents, removes non digit characters and converts the result to an integer value
    var value: Int { string.digits.integer ?? 0 }

    var maxValue: Int = 999_999_999
    private var lastValue: Int = 0

    override func willMove(toSuperview newSuperview: UIView?) {
        // adds a target to the textfield to monitor when the text changes
        addTarget(self, action: #selector(editingChanged), for: .editingChanged)
        // sets the keyboard type to digits only
        keyboardType = .numberPad
        // set the text alignment to right
        textAlignment = .right
        // sends an editingChanged action to force the textfield to be updated
        sendActions(for: .editingChanged)
    }
    // deletes the last digit of the text field
    override func deleteBackward() {
        // note that the field text property default value is an empty string so force unwrap its value is safe
        // note also that collection remove at requires a non empty collection which is true as well in this case so no need to check if the collection is not empty.
        text!.remove(at: text!.index(before: text!.endIndex))
        // sends an editingChanged action to force the textfield to be updated
        sendActions(for: .editingChanged)
    }
    @objc func editingChanged() {
        guard value <= maxValue else {
            text = Formatter.decimal.string(for: lastValue)
            return
        }
        // This will format the textfield respecting the user device locale and settings
        text = Formatter.decimal.string(for: value)
        print("Value:", value)
        lastValue = value
    }
}


You would need to add those extensions to your project as well:

您还需要将这些扩展添加到您的项目中:



Extensions UITextField.swiftfile contents:

扩展 UITextField.swift文件内容:

import UIKit
extension UITextField {
    var string: String { text ?? "" }
}


Extensions Formatter.swiftfile contents:

扩展 Formatter.swift文件内容:

import Foundation
extension Formatter {
    static let decimal = NumberFormatter(numberStyle: .decimal)
}


Extensions NumberFormatter.swiftfile contents:

扩展 NumberFormatter.swift文件内容:

import Foundation
extension NumberFormatter {
    convenience init(numberStyle: Style) {
        self.init()
        self.numberStyle = numberStyle
    }
}


Extensions StringProtocol.swiftfile contents:

扩展 StringProtocol.swift文件内容:

extension StringProtocol where Self: RangeReplaceableCollection {
    var digits: Self { filter(\.isWholeNumber) }
    var integer: Int? { Int(self) }
}


Sample project

示例项目

回答by Abaho Katabarwa

You can use NSNumberFormatter().numberFromString(yourNumberString). It's great because it returns an an optional that you can then test with if letto determine if the conversion was successful. eg.

您可以使用NSNumberFormatter().numberFromString(yourNumberString). 这很棒,因为它返回一个可选项,然后您可以用它if let来测试以确定转换是否成功。例如。

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
}

Swift 5

斯威夫特 5

var myString = "\(10)"
if let myNumber = NumberFormatter().number(from: myString) {
    var myInt = myNumber.intValue
    // do what you need to do with myInt
  } else {
    // what ever error code you need to write
  }

回答by OOMMEN

swift 4.0

迅捷 4.0

let stringNumber = "123"
let number = Int(stringNumber) //here number is of type "Int?"


//using Forced Unwrapping

if number != nil {         
 //string is converted to Int
}

you could also use Optional Binding other than forced binding.

除了强制绑定之外,您还可以使用可选绑定。

eg:

例如:

  if let number = Int(stringNumber) { 
   // number is of type Int 
  }

回答by Pankaj Nigam

//Xcode 8.1 and swift 3.0

//Xcode 8.1 和 swift 3.0

We can also handle it by Optional Binding, Simply

我们也可以通过Optional Binding来处理,简单的

let occur = "10"

if let occ = Int(occur) {
        print("By optional binding :", occ*2) // 20

    }

回答by iOS

In Swift 4.2and Xcode 10.1

Swift 4.2Xcode 10.1 中

let string:String = "789"
let intValue:Int = Int(string)!
print(intValue)

let integerValue:Int = 789
let stringValue:String = String(integerValue)
    //OR
//let stringValue:String = "\(integerValue)"
print(stringValue)

回答by Ankit garg

In Swift 4:

在 Swift 4 中:

extension String {            
    var numberValue:NSNumber? {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        return formatter.number(from: self)
    }
}
let someFloat = "12".numberValue

回答by torcelly

Swift 3

斯威夫特 3

The simplest and more secure way is:

最简单、更安全的方法是:

@IBOutlet var textFieldA  : UITextField
@IBOutlet var textFieldB  : UITextField
@IBOutlet var answerLabel : UILabel

@IBAction func calculate(sender : AnyObject) {

      if let intValueA = Int(textFieldA),
            let intValueB = Int(textFieldB) {
            let result = intValueA + intValueB
            answerLabel.text = "The acceleration is \(result)"
      }
      else {
             answerLabel.text = "The value \(intValueA) and/or \(intValueB) are not a valid integer value"
      }        
}

Avoid invalid values setting keyboard type to number pad:

避免将键盘类型设置为数字键盘的无效值:

 textFieldA.keyboardType = .numberPad
 textFieldB.keyboardType = .numberPad