该应用程序基本上通过输入初始和最终速度和时间来计算加速度,然后使用一个公式来计算加速度。但是,由于文本框中的值是字符串,我无法将它们转换为整数。
@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) }
}
示例项目
Swift 5.0及以上
工作
如果你拆分字符串,它会创建两个子字符串,而不是两个字符串。下面的方法将检查任何并将其转换为0 NSNumber很容易将NSNumber转换为Int,浮动任何你需要的数据类型。
实际的代码
//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 {
}
传递字符串进行检查并转换为Double
Double(getNumber(number: dict["OUT"] ?? 0)
斯威夫特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