可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
The application basically calculates acceleration by inputting Initial and final velocity and time and then use a formula to calculate acceleration. However, since the values in the text boxes are string, I am unable to convert them to integers.
@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
回答1:
Basic Idea, note that this only works in Swift 1.x (check out ParaSara\'s answer to see how it works in 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\"
}
Update for Swift 4
...
let a:Int? = Int(firstText.text) // firstText is UITextField
let b:Int? = Int(secondText.text) // secondText is UITextField
...
回答2:
Update Answer for swift 2.0 :
toInt()
method is given a error. Because,In Swift 2.x, the .toInt()
function was removed from String. In replacement, Int now has an initializer that accepts a String:
let a:Int? = Int(firstText.text) // firstText is UITextField
let b:Int? = Int(secondText.text) // secondText is UITextField
回答3:
myString.toInt()
- convert the string value into int .
Swift 3.x
If you have an integer hiding inside a string, you can convertby using the integer\'s constructor, like this:
let myInt = Int(textField.text)
As with other data types (Float and Double) you can also convert by using NSString:
let myString = \"556\"
let myInt = (myString as NSString).integerValue
回答4:
Xcode 8.3.2 • Swift 3.1
class IntegerField: UITextField {
var integer: Int {
return string.digits.integer
}
override func willMove(toSuperview newSuperview: UIView?) {
addTarget(self, action: #selector(editingChanged), for: .editingChanged)
keyboardType = .numberPad
textAlignment = .right
editingChanged()
}
func editingChanged() {
text = Formatter.decimal.string(for: integer)
print(integer)
}
}
Required extensions, structs and initializers:
extension Sequence where Iterator.Element == UnicodeScalar {
var string: String { return String(String.UnicodeScalarView(self)) }
}
extension Formatter {
static let decimal = NumberFormatter(numberStyle: .decimal)
}
extension UITextField {
var string: String { return text ?? \"\" }
}
extension String {
private static var digitsPattern = UnicodeScalar(\"0\")...\"9\"
var digits: String {
return unicodeScalars.filter { String.digitsPattern ~= $0 }.string
}
var integer: Int { return Int(self) ?? 0 }
}
extension NumberFormatter {
convenience init(numberStyle: Style) {
self.init()
self.numberStyle = numberStyle
}
}
回答5:
You wanna use NSNumberFormatter().numberFromString(yourNumberString)
. It\'s great because it returns an an optional that you can then test with an \"if let\" to determine if the conversion was successful.
eg.
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
}
回答6:
swift 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
}
you could also use Optional Binding other than forced binding.
eg:
if let number = Int(stringNumber) {
// number is of type Int
}
回答7:
//Xcode 8.1 and swift 3.0
We can also handle it by Optional Binding, Simply
let occur = \"10\"
if let occ = Int(occur) {
print(\"By optional binding :\", occ*2) // 20
}
回答8:
Swift 3
The simplest and more secure way is:
@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\"
}
}
Avoid invalid values setting keyboard type to number pad:
textFieldA.keyboardType = .numberPad
textFieldB.keyboardType = .numberPad
回答9:
In Swift 4:
extension String {
var numberValue:NSNumber? {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
return formatter.number(from: self)
}
}
let someFloat = \"12\".numberValue
回答10:
i have made a simple program, where you have 2 txt field you take input form the user and add them to make it simpler to understand please find the code below.
@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)\"
}
hope this helps.
回答11:
About int() and Swift 2.x: if you get a nil value after conversion check if you try to convert a string with a big number (for example: 1073741824), in this case try:
let bytesInternet : Int64 = Int64(bytesInternetString)!
回答12:
Latest swift3 this code is simply to convert string to int
let myString = \"556\"
let myInt = Int(myString)
回答13:
Swift 3.0
Try this, you don\'t need to check for any condition I have done everything just use this function. Send anything string, number, float, double ,etc,. you get a number as a value or 0 if it is unable to convert your value
Function:
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
}
Usage:
Add the above function in code and to convert use
let myNumber = getNumber(number: myString)
if the myString
has a number or string it returns the number else it returns 0
Example 1:
let number:String = \"9834\"
print(\"printing number \\(getNumber(number: number))\")
Output: printing number 9834
Example 2:
let number:Double = 9834
print(\"printing number \\(getNumber(number: number))\")
Output: printing number 9834
Example 3:
let number = 9834
print(\"printing number \\(getNumber(number: number))\")
Output: printing number 9834
回答14:
In Swift 4.2 and Xcode 10.1
let string:String = \"789\"
let intValue:Int = Int(string)!
print(intValue)
let integerValue:Int = 789
let stringValue:String = String(integerValue)
//OR
//let stringValue:String = \"\\(integerValue)\"
print(stringValue)
回答15:
Because a string might contain non-numerical characters you should use a guard
to protect the operation. Example:
guard let labelInt:Int = Int(labelString) else {
return
}
useLabelInt()
回答16:
Use this:
// 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\"
}
OR
Make your UITextField KeyboardType as DecimalTab from your XIB or storyboard, and remove any if condition for doing any calculation, ie.
var ans = a + b
answerLabel.text = \"Answer is \\(ans)\"
Because keyboard type is DecimalPad there is no chance to enter other 0-9 or .
Hope this help !!
回答17:
// 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);
回答18:
This works for me
var a:Int? = Int(userInput.text!)
回答19:
for Swift3.x
extension String {
func toInt(defaultValue: Int) -> Int {
if let n = Int(self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)) {
return n
} else {
return defaultValue
}
}
}
回答20:
In Swift 2.x, the .toInt() function was removed from String. In replacement, Int now has an initializer that accepts a String
Int(myString)
In your case, you could use Int(textField.text!) insted of textField.text!.toInt()
Swift 1.x
let myString: String = \"256\"
let myInt: Int? = myString.toInt()
Swift 2.x, 3.x
let myString: String = \"256\"
let myInt: Int? = Int(myString)
回答21:
for Alternative solution. You can use extension a native type. You can test with playground.
extension String {
func add(a: Int) -> Int? {
if let b = Int(self) {
return b + a
}
else {
return nil
}
}
}
\"2\".add(1)
回答22:
My solution is to have a general extension for string to int conversion.
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
}
}
}
回答23:
@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
}
回答24:
As of swift 3, I have to force my #%@! string & int with a \"!\" otherwise it just doesn\'t work.
For example:
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
回答25:
Question : string \"4.0000\" can not be convert into integer using Int(\"4.000\")?
Answer : Int() check string is integer or not if yes then give you integer and otherwise nil. but Float or Double can convert any number string to respective Float or Double without giving nil. Example if you have \"45\" integer string but using Float(\"45\") gives you 45.0 float value or using Double(\"4567\") gives you 45.0.
Solution : NSString(string: \"45.000\").integerValue or Int(Float(\"45.000\")!)! to get correct result.
回答26:
I recently got the same issue. Below solution is work for me:
let strValue = \"123\"
let result = (strValue as NSString).integerValue
回答27:
Convert String value to Integer in Swift 4
let strValue:String = \"100\"
let intValue = strValue as! Int
var intValueFromString:Int = strValue as! Int
or
var intValueFromString = Int(strValue)!
回答28:
let string = \"1234.234\"
let result1 = Double(string)
let result2 = (string as NSString).doubleValue
It works in swift 4. It suits for int too.