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
Swift 2.0 you can initialize Integer using constructor
var stringNumber = "1234"
var numberFromString = Int(stringNumber)
In Swift 3.0
Type 1: Convert NSString to String
let stringNumb:NSString = "1357"
let someNumb = Int(stringNumb as String) // 1357 as integer
Type 2: If the String has Integer only
let stringNumb = "1357"
let someNumb = Int(stringNumb) // 1357 as integer
Type 3: If the String has Float value
let stringNumb = "13.57"
if let stringToFloat = Float(stringNumb){
let someNumb = Int(stringToFloat)// 13 as Integer
}else{
//do something if the stringNumb not have digit only. (i.e.,) let stringNumb = "13er4"
}
Simple but dirty way
// Swift 1.2
if let intValue = "42".toInt() {
let number1 = NSNumber(integer:intValue)
}
// Swift 2.0
let number2 = Int(stringNumber)
// Using NSNumber
let number3 = NSNumber(float:("42.42" as NSString).floatValue)
The extension-way
This is better, really, because it'll play nicely with locales and decimals.
extension String {
var numberValue:NSNumber? {
let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
return formatter.numberFromString(self)
}
}
Now you can simply do:
let someFloat = "42.42".numberValue
let someInt = "42".numberValue
If you are able to use a NSString
only.
It's pretty similar to objective-c. All the data type are there but require the as NSString
addition
var x = "400.0" as NSString
x.floatValue //string to float
x.doubleValue // to double
x.boolValue // to bool
x.integerValue // to integer
x.intValue // to int
Also we have an toInt()
function added See Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l page 49
x.toInt()
A more general solution could be a extension
extension String {
var toFloat:Float {
return Float(self.bridgeToObjectiveC().floatValue)
}
var toDouble:Double {
....
}
....
}
this for example extends the swift native String object by toFloat
8:1 Odds(*)
var stringNumb: String = "1357"
var someNumb = Int(stringNumb)
or
var stringNumb: String = "1357"
var someNumb:Int? = Int(stringNumb)
Int(String)
returns an optional Int?
, not an Int
.
Safe use: do not explicitly unwrap
let unwrapped:Int = Int(stringNumb) ?? 0
or
if let stringNumb:Int = stringNumb { ... }
(*) None of the answers actually addressed why var someNumb: Int = Int(stringNumb)
was not working.