用Swift将字符串转换为Int

该应用程序基本上通过输入初始和最终速度和时间来计算加速度,然后使用一个公式来计算加速度。但是,由于文本框中的值是字符串,我无法将它们转换为整数。

@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
586827 次浏览

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

快3.倍

如果你在字符串中隐藏了一个整数,你可以使用整数的构造函数进行转换,如下所示:

let myInt = Int(textField.text)

与其他数据类型(Float和Double)一样,你也可以使用NSString进行转换:

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

基本思想,注意,这只适用于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"
}

Swift 4更新

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

用这个:

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

使你的UITextField KeyboardType为DecimalTab从你的XIB或故事板,并删除任何if条件做任何计算,即。

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

因为键盘类型是DecimalPad,没有机会输入其他0-9或。

希望这对你有帮助!!

你可以使用NSNumberFormatter().numberFromString(yourNumberString)。这很好,因为它返回一个可选的,然后你可以用if let测试,以确定转换是否成功。 如。< / p >
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
}

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

Swift 2.0+的更新答案:

toInt()方法给出了一个错误,因为它在Swift 2.x中从String中删除了。相反,Int类型现在有一个接受String的初始化式:

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

这对我很有用

var a:Int? = Int(userInput.text!)

关于int()和Swift 2。X:如果你尝试转换一个大数字的字符串(例如:1073741824),在转换检查后得到nil值,在这种情况下尝试:

let bytesInternet : Int64 = Int64(bytesInternetString)!
//  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);

编辑/更新:Xcode 11.4•Swift 5.2

请检查代码中的注释


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

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


扩展UITextField.swift文件内容:

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

扩展Formatter.swift文件内容:

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

扩展NumberFormatter.swift文件内容:

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

扩展StringProtocol.swift文件内容:

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

样本项目 .

我已经做了一个简单的程序,其中有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)"
}

希望这能有所帮助。

为替代方案。您可以对本机类型使用扩展。你可以在操场上测试。

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

“2”阀门(1)

斯威夫特3

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

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

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

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

//Xcode 8.1和swift 3.0

我们也可以通过可选绑定来处理它

let occur = "10"


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


}

我的解决方案是有一个一般的扩展字符串到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
}
}


}

斯威夫特3.0

试试这个,你不需要检查任何条件,我已经做了一切,只是使用这个函数。发送任何字符串,数字,浮点数,双精度等。你得到一个数字作为一个值,或0如果它不能转换你的值

功能:

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
}

< >强用法: 在代码中添加上述函数并转换使用 let myNumber = getNumber(number: myString) 如果myString包含数字或字符串,则返回数字,否则返回0

示例1:

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

输出:printing number 9834

示例2:

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

输出:printing number 9834

示例3:

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

输出:printing number 9834

最新swift3此代码简单地将字符串转换为int

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

对于Swift3.x

extension String {
func toInt(defaultValue: Int) -> Int {
if let n = Int(self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)) {
return n
} else {
return defaultValue
}
}
}
@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
}

在Swift 4中:

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

对于斯威夫特3,我必须强制我的#%@!字符串,Int加上一个“!”,否则它就不起作用。

例如:

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

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

你也可以使用可选绑定而不是强制绑定。

例如:

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

问题:字符串“4.000”不能转换成整数使用Int(“4.000”)?

答案:Int()检查字符串是否是整数,如果是,然后给你整数,否则为nil。但是Float或Double可以将任何数字字符串转换为各自的Float或Double而不给nil。例如,如果你有“45”整数字符串,但使用Float("45")会给你45.0浮点值,或使用Double("4567")会给你45.0。

解决方案:NSString(string: "45.000").integerValue或Int(Float("45.000")!)!才能得到正确的结果。

因为字符串可能包含非数字字符,所以应该使用guard来保护操作。例子:

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


useLabelInt()

我最近也遇到了同样的问题。下面的解决方案对我来说是可行的:

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

斯威夫特4.2Xcode 10.1

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

let integerValue = 789
let stringValue = String(integerValue)

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

转换字符串值为整数在Swift 4

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

Swift中的Int包含一个接受String的初始化式。它返回一个可选的Int?因为如果字符串不包含数字,转换可能会失败。

通过使用if let语句,可以验证转换是否成功。

所以你的代码会变成这样:

@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
}
}

有用的字符串到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
}
}

像这样使用它:

"123".toInt() // 123

Swift 5.0及以上

工作

如果你正在分割String,它会创建两个substrings而不是两个Strings。下面的方法将检查Any并将其转换为0 NSNumber很容易将NSNumber转换为IntFloat以及任何你需要的数据类型。

实际的代码

//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 }

使用

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


}

传递String来检查并转换为Double

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

Swift5 float或int string to int:

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())

斯威夫特,斯威夫特

有不同的情况下,从一个数据类型转换到另一个数据类型,这取决于输入。

如果输入数据类型是Any,我们必须在转换为实际数据类型之前使用as,然后转换为我们想要的数据类型。例如:

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