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

@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

当前回答

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

示例项目

其他回答

问题:字符串“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")!)!才能得到正确的结果。

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

希望这能有所帮助。

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

}

//Xcode 8.1和swift 3.0

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

let occur = "10"

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

    }

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

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