简体   繁体   English

使用 Swift 将 String 转换为 Int

[英]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

Updated answer for Swift 2.0+ : Swift 2.0+ 的更新答案

toInt() method gives an error, as it was removed from String in Swift 2.x. toInt()方法会报错,因为它在 Swift 2.x 中已从String中删除。 Instead, the Int type now has an initializer that accepts a String :相反, Int类型现在有一个接受String的初始化程序:

let a: Int? = Int(firstTextField.text)
let b: Int? = Int(secondTextField.text)

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
...

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

You can use NSNumberFormatter().numberFromString(yourNumberString) .您可以使用NSNumberFormatter().numberFromString(yourNumberString) It's great because it returns an an optional that you can then test with 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
}

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
  }

edit/update: Xcode 11.4 • Swift 5.2编辑/更新: Xcode 11.4 • Swift 5.2

Please check the comments through the code请通过代码查看评论


IntegerField.swift file 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.swift file contents:扩展 UITextField.swift文件内容:

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

Extensions Formatter.swift file contents: Extensions Formatter.swift文件内容:

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

Extensions NumberFormatter.swift file contents:扩展 NumberFormatter.swift文件内容:

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

Extensions StringProtocol.swift file contents:扩展 StringProtocol.swift文件内容:

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

Sample project 示例项目

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 
  }

//Xcode 8.1 and swift 3.0 //Xcode 8.1 和 swift 3.0

We can also handle it by Optional Binding, Simply我们也可以通过 Optional Binding 来处理,Simply

let occur = "10"

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

    }

In Swift 4.2 and Xcode 10.1Swift 4.2Xcode 10.1

let string = "789"
if let intValue = Int(string) {
    print(intValue)
}

let integerValue = 789
let stringValue = String(integerValue)

OR或者

let stringValue = "\(integerValue)"
print(stringValue)

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

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

Useful for String to Int and other type对 String 到 Int 和其他类型很有用

extension String {
        //Converts String to Int
        public func toInt() -> Int? {
            if let num = NumberFormatter().number(from: self) {
                return num.intValue
            } else {
                return nil
            }
        }

        //Converts String to Double
        public func toDouble() -> Double? {
            if let num = NumberFormatter().number(from: self) {
                return num.doubleValue
            } else {
                return nil
            }
        }

        /// EZSE: Converts String to Float
        public func toFloat() -> Float? {
            if let num = NumberFormatter().number(from: self) {
                return num.floatValue
            } else {
                return nil
            }
        }

        //Converts String to Bool
        public func toBool() -> Bool? {
            return (self as NSString).boolValue
        }
    }

Use it like :像这样使用它:

"123".toInt() // 123

i have made a simple program, where you have 2 txt field you take input form the user and add them to make it simpler to understand please find the code below.我制作了一个简单的程序,其中您有 2 个 txt 字段,您可以从用户那里获取输入并添加它们以使其更易于理解,请在下面找到代码。

@IBOutlet weak var result: UILabel!
@IBOutlet weak var one: UITextField!
@IBOutlet weak var two: UITextField!

@IBAction func add(sender: AnyObject) {        
    let count = Int(one.text!)
    let cal = Int(two.text!)
    let sum = count! + cal!
    result.text = "Sum is \(sum)"
}

hope this helps.希望这可以帮助。

Swift 3.0斯威夫特 3.0

Try this, you don't need to check for any condition I have done everything just use this function.试试这个,你不需要检查任何条件我已经完成了一切,只需使用这个功能。 Send anything string, number, float, double ,etc,.发送任何字符串、数字、浮点数、双精度等。 you get a number as a value or 0 if it is unable to convert your value如果无法转换您的值,您将获得一个数字作为值或 0

Function:功能:

func getNumber(number: Any?) -> NSNumber {
    guard let statusNumber:NSNumber = number as? NSNumber else
    {
        guard let statString:String = number as? String else
        {
            return 0
        }
        if let myInteger = Int(statString)
        {
            return NSNumber(value:myInteger)
        }
        else{
            return 0
        }
    }
    return statusNumber
}

Usage: Add the above function in code and to convert use let myNumber = getNumber(number: myString) if the myString has a number or string it returns the number else it returns 0用法:在代码中添加上述函数并转换使用let myNumber = getNumber(number: myString)如果myString有数字或字符串,则返回数字,否则返回0

Example 1:示例 1:

let number:String = "9834"
print("printing number \(getNumber(number: number))")

Output: printing number 9834输出: printing number 9834

Example 2:示例 2:

let number:Double = 9834
print("printing number \(getNumber(number: number))")

Output: printing number 9834输出: printing number 9834

Example 3:示例 3:

let number = 9834
print("printing number \(getNumber(number: number))")

Output: printing number 9834输出: printing number 9834

关于 int() 和 Swift 2.x:如果您在转换后得到一个 nil 值,请检查您是否尝试转换具有大数字的字符串(例如:1073741824),在这种情况下尝试:

let bytesInternet : Int64 = Int64(bytesInternetString)!

Latest swift3 this code is simply to convert string to int最新的 swift3这段代码只是将字符串转换为 int

let myString = "556"
let myInt = Int(myString)

Because a string might contain non-numerical characters you should use a guard to protect the operation.因为字符串可能包含非数字字符,所以您应该使用guard来保护操作。 Example:例子:

guard let labelInt:Int = Int(labelString) else {
    return
}

useLabelInt()

I recently got the same issue.我最近遇到了同样的问题。 Below solution is work for me:以下解决方案对我有用:

        let strValue = "123"
        let result = (strValue as NSString).integerValue

Swift5 float or int string to int: Swift5 将浮点数或整数字符串转换为整数:

extension String {
    func convertStringToInt() -> Int {
        return Int(Double(self) ?? 0.0)
    }
}

let doubleStr = "4.2"
// print 4
print(doubleStr.convertStringToInt())

let intStr = "4"
// print 4
print(intStr.convertStringToInt())

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.将您的 UITextField KeyboardType 从您的 XIB 或情节提要中设为 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 !!希望这有帮助!

这对我有用

var a:Int? = Int(userInput.text!)
//  To convert user input (i.e string) to int for calculation.I did this , and it works.


    let num:Int? = Int(firstTextField.text!);

    let sum:Int = num!-2

    print(sum);

for Swift3.x对于 Swift3.x

extension String {
    func toInt(defaultValue: Int) -> Int {
        if let n = Int(self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)) {
            return n
        } else {
            return defaultValue
        }
    }
}

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的初始化器

Int(myString) INT(MyString的)

In your case, you could use Int(textField.text!) insted of textField.text!.toInt() 在您的情况下,您可以使用textField.text!.toInt()的Int(textField.text!)

Swift 1.x Swift 1.x

let myString: String = "256"
let myInt: Int? = myString.toInt()

Swift 2.x, 3.x Swift 2.x,3.x

let myString: String = "256"
let myInt: Int? = Int(myString)

Swift 4, Swift 5斯威夫特 4,斯威夫特 5

There are different cases to convert from something to something data type, it depends the input.有不同的情况可以从某物转换为某物数据类型,这取决于输入。

If the input data type is Any , we have to use as before convert to actual data type, then convert to data type what we want.如果输入数据类型是Any ,我们必须as以前一样使用转换为实际数据类型,然后转换为我们想要的数据类型。 For example:例如:

func justGetDummyString() -> Any {
  return "2000"
}
let dummyString: String = (justGetDummyString() as? String) ?? "" // output = "2000"
let dummyInt: Int = Int(dummyString) ?? 0 // output = 2000

for Alternative solution.替代解决方案。 You can use extension a native type.您可以使用扩展本机类型。 You can test with playground.您可以在操场上进行测试。

extension String {
    func add(a: Int) -> Int? {
        if let b = Int(self) {
            return b + a
        }
        else {
            return nil
        }
    }     
}

"2".add(1) “2”.add(1)

My solution is to have a general extension for string to int conversion.我的解决方案是对字符串到 int 的转换进行一般扩展。

extension String {

 // default: it is a number suitable for your project if the string is not an integer

    func toInt(default: Int) -> Int {
        if let result = Int(self) {
            return result
        }
        else {
            return default  
        }
    }

}
@IBAction func calculateAclr(_ sender: Any) {
    if let addition = addition(arrayString: [txtBox1.text, txtBox2.text, txtBox3.text]) {
      print("Answer = \(addition)")
      lblAnswer.text = "\(addition)"
    }
}

func addition(arrayString: [Any?]) -> Int? {

    var answer:Int?
    for arrayElement in arrayString {
        if let stringValue = arrayElement, let intValue = Int(stringValue)  {
            answer = (answer ?? 0) + intValue
        }
    }

    return answer
}

Question : string "4.0000" can not be convert into integer using Int("4.000")?问题:字符串“4.0000”不能使用 Int(“4.000”) 转换为整数?

Answer : Int() check string is integer or not if yes then give you integer and otherwise nil.答案: Int() 检查字符串是否为整数,如果是,则给您整数,否则为零。 but Float or Double can convert any number string to respective Float or Double without giving nil.但是 Float 或 Double 可以将任何数字字符串转换为相应的 Float 或 Double 而无需给出 nil。 Example if you have "45" integer string but using Float("45") gives you 45.0 float value or using Double("4567") gives you 45.0.例如,如果您有“45”整数字符串,但使用 Float("45") 会得到 45.0 浮点值,或者使用 Double("4567") 会得到 45.0。

Solution : NSString(string: "45.000").integerValue or Int(Float("45.000")!)!解决方案: NSString(string: "45.000").integerValue 或 Int(Float("45.000")!)! to get correct result.得到正确的结果。

An Int in Swift contains an initializer that accepts a String. Swift 中的 Int 包含一个接受 String 的初始化程序。 It returns an optional Int?它返回一个可选的 Int? as the conversion can fail if the string contains not a number.因为如果字符串不包含数字,转换可能会失败。

By using an if let statement you can validate whether the conversion succeeded.通过使用 if let 语句,您可以验证转换是否成功。

So your code become something like this:所以你的代码变成了这样:

@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

    if let intAnswer = Int(txtBox1.text) {
      // Correctly converted
    }
}

Swift 5.0 and Above Swift 5.0 及更高版本

Working在职的

In case if you are splitting the String it creates two substrings and not two Strings .如果您要拆分String ,它会创建两个substrings而不是两个Strings This below method will check for Any and convert it t0 NSNumber its easy to convert a NSNumber to Int , Float what ever data type you need.下面的方法将检查Any并将其转换为 t0 NSNumber很容易将NSNumber转换为IntFloat您需要的任何数据类型。

Actual Code实际代码

//Convert Any To Number Object Removing Optional Key Word.
public func getNumber(number: Any) -> NSNumber{
 guard let statusNumber:NSNumber = number as? NSNumber  else {
    guard let statString:String = number as? String else {
        guard let statSubStr : Substring = number as? Substring else {
            return 0
        }
        if let myInteger = Int(statSubStr) {
            return NSNumber(value:myInteger)
        }
        else{
            return 0
        }
    }

    if let myInteger = Int(statString) {
        return NSNumber(value:myInteger)
    }
    else if let myFloat = Float(statString) {
        return NSNumber(value:myFloat)
    }else {
        return 0
    }
}
return statusNumber }

Usage用法

if let hourVal = getNumber(number: hourStr) as? Int {

}

Passing String to check and convert to Double传递String以检查并转换为Double

Double(getNumber(number:  dict["OUT"] ?? 0)

As of swift 3 , I have to force my #%@!swift 3开始,我必须强制我的 #%@! string & int with a "!"带“!”的字符串和整数otherwise it just doesn't work.否则它就是行不通的。

For example:例如:

let prefs = UserDefaults.standard
var counter: String!
counter = prefs.string(forKey:"counter")
print("counter: \(counter!)")


var counterInt = Int(counter!)
counterInt = counterInt! + 1
print("counterInt: \(counterInt!)")

OUTPUT:
counter: 1
counterInt: 2

Convert String value to Integer in Swift 4在 Swift 4 中将字符串值转换为整数

let strValue:String = "100"
let intValue = strValue as! Int
var intValueFromString:Int = strValue as! Int
or
var intValueFromString = Int(strValue)!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM