According to Swift - Converting String to Int, there's a String
method toInt()
.
But, there's no toUInt()
method. So, how to convert a String
to a Uint
?
Using NSString We can convert a numeric string into an integer value indirectly. Firstly, we can convert a string into an NSString then we can use “integerValue” property used with NSStrings to convert an NSString into an integer value.
Use Integer.parseInt() to Convert a String to an Integer This method returns the string as a primitive type int. If the string does not contain a valid integer then it will throw a NumberFormatException.
An unsigned integer value type.
// Swift program to convert an optional string // into the normal string import Swift; var str:String=""; print("Enter String:"); str = readLine()!; print("String is: ",str); Output: Enter String: Hello World String is: Hello World ... Program finished with exit code 0 Press ENTER to exit console.
Use Forced Unwrapping or Optional Binding to make sure the string can be converted to UInt. eg:
let string = "123"
let number = UInt(string) //here number is of type *optional UInt*
//Forced Unwrapping
if number != nil {
//converted to type UInt
}
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