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

@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

当前回答

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

其他回答

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

示例项目

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

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

示例1:

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

输出:打印号9834

示例2:

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

输出:打印号9834

示例3:

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

输出:打印号9834

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

希望这能有所帮助。

对于Swift3.x

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

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

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