So I can do this:
var stringNumb: NSString = \"1357\"
var someNumb: CInt = stringNumb.intValue
But I can\'t find the way to do it w/ a
Convert String to Int in Swift 2.0:
var str:NSString = Data as! NSString
var cont:Int = str.integerValue
use .intergerValue or intValue for Int32
The method you want is toInt()
-- you have to be a little careful, since the toInt()
returns an optional Int.
let stringNumber = "1234"
let numberFromString = stringNumber.toInt()
// numberFromString is of type Int? with value 1234
let notANumber = "Uh oh"
let wontBeANumber = notANumber.toInt()
// wontBeANumber is of type Int? with value nil
above answer didnt help me as my string value was "700.00"
with Swift 2.2 this works for me
let myString = "700.00"
let myInt = (myString as NSString).integerValue
I passed myInt to NSFormatterClass
let formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
formatter.maximumFractionDigits = 0
let priceValue = formatter.stringFromNumber(myInt!)!
//Now priceValue is ₹ 700
Thanks to this blog post.
You can bridge from String to NSString and convert from CInt to Int like this:
var myint: Int = Int(stringNumb.bridgeToObjectiveC().intValue)
I'd use:
var stringNumber = "1234"
var numberFromString = stringNumber.toInt()
println(numberFromString)
Note toInt()
:
If the string represents an integer that fits into an Int, returns the corresponding integer.
I wrote an extension for that purpose. It always returns an Int
. If the string does not fit into an Int
, 0 is returned.
extension String {
func toTypeSafeInt() -> Int {
if let safeInt = self.toInt() {
return safeInt
} else {
return 0
}
}
}