.toInt() removed in Swift 2? - swift

I was working on an application that used a text field and translated it into an integer. Previously my code
textField.text.toInt()
worked. Now Swift declares this as an error and is telling me to do
textField.text!.toInt()
and it says there is no toInt() and to try using Int(). That doesn't work either. What just happened?

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)

Swift 2
let myString: NSString = "123"
let myStringToInt: Int = Int(myString.intValue)
declare your string as an object NSString
and use the intValue getter

Its easy enough to create your own extension method to put this back in:
extension String {
func toInt() -> Int? {
return Int(self)
}
}

I had the same issued in Payment processing apps.
Swift 1.0
let expMonth = UInt(expirationDate[0].toInt()!)
let expYear = UInt(expirationDate[1].toInt()!)
After in Swift 2.0
let expMonth = Int(expirationDate[0])
let expYear = Int(expirationDate[1])

That gave me some errors too!
This code solved my errors
let myString: String = dataEntered.text! // data entered in textField
var myInt: Int? = Int(myString) // conversion of string to Int
myInt = myInt! * 2 // manipulating the integer sum,difference,product, division
finalOutput.text! = "\(myInt)" // changes finalOutput label to myInt

Related

How to convert string to UInt32?

I am a beginner in swift and I am having a problem with convering string to UInt32.
let Generator = (ReadableJSON ["People"] [Person]["F1"].string! as NSString).doubleValue
if Generator == 1 {
NameLabel1 = ReadableJSON ["People"] [Person]["A1"].string as String!
NameImeNaObekt = ReadableJSON ["People"] [Person] ["B1"].string as String!
Picture = ReadableJSON ["People"] [Person] ["E1"].string as String!
} else {
let RGen = arc4random_uniform ("\(Generator)") // here is the error
}
Would you advise me how to fix it. The problem is in the last line, which is red and it says Cannot convert value of type String to UInt32.
The main idea is that I am reading the number from a JSON file and I have to populate this number into the arc4random_uniform.
arc4random_uniform(UInt32)
accept an UInt32 value but you are passing an String value to it
this converts your number to string
"\(Generator)"
the last line should be like this
let RGen = arc4random_uniform (UInt32(Generator))
and if you want to 'RGen' is an String you can do it this way
"\(RGen)"
String(RGen)
var RGen= 0
let RGen =int( arc4random_uniform ("\(Generator)") )
or
let RGen =( arc4random_uniform ("(Generator)") ).toInt
Look here

cannot convert a dictionary's int-value to String in swift

I have a webService, which is returning some data. here is the link http://portal.pfs-ltd.org/LoginService1114?deviceid=89A04BDB-53AA-4441-9AFD-287729ACFE7F&imeino=12345678&SerialNo=f7pln20mfpfl&username=TST0002&password=TST0002&type=agent&status=Login&flag=True&Brand=Ipad&SimSerialNumber=&TelePhoneNumber=&Model=0&InstalledVersion=1.0
I'm unable to convert the value(int) for a key to a var of type String
var ApplicationVersion: String = dict["ApplicationVersion"] as String
as is for typecasting, not converting. You need to make a string from the integer value:
let version = dict["ApplicationVersion"] as Int
let applicationVersion = "\(version)"
Note that this performs no safety checking or validation.
Your json is not a dictionary, but a nested array.
let json: [AnyObject] = ...
let dict = json[0][0] as NSDictionary
var applicationVersion = String(dict["ApplicationVersion"] as Int)

Swift double to string

Before I updated xCode 6, I had no problems casting a double to a string but now it gives me an error
var a: Double = 1.5
var b: String = String(a)
It gives me the error message "double is not convertible to string". Is there any other way to do it?
It is not casting, it is creating a string from a value with a format.
let a: Double = 1.5
let b: String = String(format: "%f", a)
print("b: \(b)") // b: 1.500000
With a different format:
let c: String = String(format: "%.1f", a)
print("c: \(c)") // c: 1.5
You can also omit the format property if no formatting is needed.
let double = 1.5
let string = double.description
update Xcode 7.1 • Swift 2.1:
Now Double is also convertible to String so you can simply use it as you wish:
let double = 1.5
let doubleString = String(double) // "1.5"
Swift 3 or later we can extend LosslessStringConvertible and make it generic
Xcode 11.3 • Swift 5.1 or later
extension LosslessStringConvertible {
var string: String { .init(self) }
}
let double = 1.5
let string = double.string // "1.5"
For a fixed number of fraction digits we can extend FloatingPoint protocol:
extension FloatingPoint where Self: CVarArg {
func fixedFraction(digits: Int) -> String {
.init(format: "%.*f", digits, self)
}
}
If you need more control over your number format (minimum and maximum fraction digits and rounding mode) you can use NumberFormatter:
extension Formatter {
static let number = NumberFormatter()
}
extension FloatingPoint {
func fractionDigits(min: Int = 2, max: Int = 2, roundingMode: NumberFormatter.RoundingMode = .halfEven) -> String {
Formatter.number.minimumFractionDigits = min
Formatter.number.maximumFractionDigits = max
Formatter.number.roundingMode = roundingMode
Formatter.number.numberStyle = .decimal
return Formatter.number.string(for: self) ?? ""
}
}
2.12345.fractionDigits() // "2.12"
2.12345.fractionDigits(min: 3, max: 3, roundingMode: .up) // "2.124"
In addition to #Zaph's answer, you can create an extension on Double:
extension Double {
func toString() -> String {
return String(format: "%.1f",self)
}
}
Usage:
var a:Double = 1.5
println("output: \(a.toString())") // output: 1.5
Swift 3+: Try these line of code
let num: Double = 1.5
let str = String(format: "%.2f", num)
to make anything a string in swift except maybe enum values simply do what you do in the println() method
for example:
var stringOfDBL = "\(myDouble)"
There are many answers here that suggest a variety of techniques. But when presenting numbers in the UI, you invariably want to use a NumberFormatter so that the results are properly formatted, rounded, and localized:
let value = 10000.5
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
guard let string = formatter.string(for: value) else { return }
print(string) // 10,000.5
If you want fixed number of decimal places, e.g. for currency values
let value = 10000.5
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2
guard let string = formatter.string(for: value) else { return }
print(string) // 10,000.50
But the beauty of this approach, is that it will be properly localized, resulting in 10,000.50 in the US but 10.000,50 in Germany. Different locales have different preferred formats for numbers, and we should let NumberFormatter use the format preferred by the end user when presenting numeric values within the UI.
Needless to say, while NumberFormatter is essential when preparing string representations within the UI, it should not be used if writing numeric values as strings for persistent storage, interface with web services, etc.
Swift 4:
Use following code
let number = 2.4
let string = String(format: "%.2f", number)
This function will let you specify the number of decimal places to show:
func doubleToString(number:Double, numberOfDecimalPlaces:Int) -> String {
return String(format:"%."+numberOfDecimalPlaces.description+"f", number)
}
Usage:
let numberString = doubleToStringDecimalPlacesWithDouble(number: x, numberOfDecimalPlaces: 2)
In swift 3:
var a: Double = 1.5
var b: String = String(a)
In swift 3 it is simple as given below
let stringDouble = String(describing: double)
I would prefer NSNumber and NumberFormatter approach (where need), also u can use extension to avoid bloating code
extension Double {
var toString: String {
return NSNumber(value: self).stringValue
}
}
U can also need reverse approach
extension String {
var toDouble: Double {
return Double(self) ?? .nan
}
}
var b = String(stringInterpolationSegment: a)
This works for me. You may have a try
In Swift 4 if you like to modify and use a Double in the UI as a textLabel "String" you can add this in the end of your file:
extension Double {
func roundToInt() -> Int{
return Int(Darwin.round(self))
}
}
And use it like this if you like to have it in a textlabel:
currentTemp.text = "\(weatherData.tempCelsius.roundToInt())"
Or print it as an Int:
print(weatherData.tempCelsius.roundToInt())
Swift 5:
Use following code
extension Double {
func getStringValue(withFloatingPoints points: Int = 0) -> String {
let valDouble = modf(self)
let fractionalVal = (valDouble.1)
if fractionalVal > 0 {
return String(format: "%.*f", points, self)
}
return String(format: "%.0f", self)
}
}
You shouldn't really ever cast a double to a string, the most common reason for casting a float to a string is to present it to a user, but floats are not real number and can only approximate lots of values, similar to how ⅓ can not be represented as a decimal number with a finite number of decimal places. Instead keep you values as float for all their use, then when you want to present them to the user, use something like NumberFormater to convert them for your. This stage of converting for user presentation is what something like your viewModel should do.
Use this.
Text(String(format: "%.2f", doubleValue))

How to cast from UInt16 to NSNumber

I have a UInt16 variable that I would like to pass to a legacy function that requires an NSNumber.
If I try:
var castAsNSNumber : NSNumber = myUInt16
I get a compiler error 'UInt16' is not convertible to 'NSNumber'
Question
How can I recast this as an NSNumber?
var castAsNSNumber = NSNumber(unsignedShort: myUInt16)
Swift 4 or newer (still works in 5.5.1):
import Foundation
let u16 = UInt16(24)
let nsnum = u16 as NSNumber
let andBack = UInt16(truncating: nsnum)
print("\(u16), \(nsnum), \(andBack)")
Try yourself:
https://swiftfiddle.com/bido2kr4x5fqnlptznxtbra76e
Or instead of
let andBack = UInt16(truncating: nsnum)
you can also use
let andBack = nsnum.uint16Value

How to convert Any to Int in Swift

I get an error when declaring i
var users = Array<Dictionary<String,Any>>()
users.append(["Name":"user1","Age":20])
var i:Int = Int(users[0]["Age"])
How to get the int value?
var i = users[0]["Age"] as Int
As GoZoner points out, if you don't know that the downcast will succeed, use:
var i = users[0]["Age"] as? Int
The result will be nil if it fails
Swift 4 answer :
if let str = users[0]["Age"] as? String, let i = Int(str) {
// do what you want with i
}
If you are sure the result is an Int then use:
var i = users[0]["Age"] as! Int
but if you are unsure and want a nil value if it is not an Int then use:
var i = users[0]["Age"] as? Int
“Use the optional form of the type cast operator (as?) when you are
not sure if the downcast will succeed. This form of the operator will
always return an optional value, and the value will be nil if the
downcast was not possible. This enables you to check for a successful
downcast.”
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks.
https://itun.es/us/jEUH0.l
This may have worked previously, but it's not the answer for Swift 3. Just to clarify, I don't have the answer for Swift 3, below is my testing using the above answer, and clearly it doesn't work.
My data comes from an NSDictionary
print("subvalue[multi] = \(subvalue["multi"]!)")
print("as Int = \(subvalue["multi"]! as? Int)")
if let multiString = subvalue["multi"] as? String {
print("as String = \(multiString)")
print("as Int = \(Int(multiString)!)")
}
The output generated is:
subvalue[multi] = 1
as Int = nil
Just to spell it out:
a) The original value is of type Any? and the value is: 1
b) Casting to Int results in nil
c) Casting to String results in nil (the print lines never execute)
EDIT
The answer is to use NSNumber
let num = subvalue["multi"] as? NSNumber
Then we can convert the number to an integer
let myint = num.intValue
if let id = json["productID"] as? String {
self.productID = Int32(id, radix: 10)!
}
This worked for me. json["productID"] is of type Any.
If it can be cast to a string, then convert it to an Integer.