swift1min read To convert a float value to an Int, we can use the Int() constructor by passing a float value to it. Note: When we use this conversion the Integer is always rounded to the nearest downward value, like 12.752 to 12 or 6.99 to 6 .
Swift – Check if Variable/Object is Int To check if a variable or object is an Int, use is operator as shown in the following expression. where x is a variable/object. The above expression returns a boolean value: true if the variable is an Int, or false if not an Int.
To convert a string to an array, we can use the Array() intializer syntax in Swift. Here is an example, that splits the following string into an array of individual characters. Similarly, we can also use the map() function to convert it. The map() function iterates each character in a string.
Swift 2.0 you can initialize Integer using constructor
var stringNumber = "1234"
var numberFromString = Int(stringNumber)
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.
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"
}
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
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With