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

@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

当前回答

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

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

eg:

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

其他回答

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

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

useLabelInt()

编辑/更新: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) }
}

示例项目

你可以使用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
}

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

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

let bytesInternet : Int64 = Int64(bytesInternetString)!

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