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
?
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
?
Use Forced Unwrapping or Optional Binding to make sure the string can be converted to UInt. eg:
You might be interested in a safer solution similar to:
Hope this helps
// Edited following @Martin R. suggestion
Please, for the love of not crashing, don’t use
!
to do this.It’s easy to tack a
map
on the end oftoInt
to convert it to an optionalUInt
:then use the usual unwrapping techniques on
myUInt
.And if you find yourself doing this a lot:
edit: as @MartinR points out, while safe, this doesn’t extract the full range of possible values for a
UInt
thatInt
doesn’t cover, see the other two answers.Update for Swift 2/Xcode 7:
As of Swift 2, all integer types have a (failable) constructor
which replaces the
toInt()
method ofString
, so no custom code is needed anymore for this task:Old answer for Swift 1.x:
This looks a bit complicated, but should work for all numbers in the full range of
UInt
, and detect all possible errors correctly (such as overflow or trailing invalid characters):Remarks:
The BSD library function
strtoul
is used for the conversion. TheendPtr
is set to first "invalid character" in the input string, thereforeendPtr.memory == 0
must be hold if all characters could be converted. In the case of a conversion error, the globalerrno
variable is set to a non-zero value (e.g.ERANGE
for an overflow).The test for a minus sign is necessary because
strtoul()
accepts negative numbers (which are converted to the unsigned number with the same bit pattern).A Swift string is converted to a C string "behind the scenes" when passed to a function taking a
char *
parameter, so one could be tempted to callstrtoul(self, &endPtr, 0)
(which is what I did in the first version of this answer). The problem is that the automatically created C string is only temporary and can already be invalid whenstrtoul()
returns, so thatendPtr
does not point to a character in the input string anymore. This happened when I tested the code in the Playground. Withself.withCString { ... }
, this problem does not occur because the C string is valid throughout the execution of the closure.Some tests:
just use UInt's init: