Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: How to convert String to UInt?

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?

like image 435
ma11hew28 Avatar asked May 21 '15 19:05

ma11hew28


People also ask

How do I convert a string to int in Swiftui?

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.

How do I convert a string to an int?

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.

What is Uint in Swift?

An unsigned integer value type.

How do I change a string from optional to string in Swift?

// 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.


1 Answers

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
}
like image 194
OOMMEN Avatar answered Oct 26 '22 05:10

OOMMEN