Tip: Creating an Int from a String in Swift

QuickTip
Talking to a couple of developers over various mediums about Swift has had mixed results. However one thing that came up again and again was that it is a little confusing. While confusing in the literal sense would not be the correct word. So let me elaborate the issue first.
If you have an Int in swift, and you want to pass the API a CGFloat , you simply cast it as CGFloat(number) . If it was say between a GCFloat and a Double , the same would apply as there is an init function that allows you to convert to the new type.

The most common trouble that many developers I spoke to found were in the conversion between Int and String. Perhaps a reason being that in most cases these two are commonly convertible in most languages like Visual Basic, Lua, etc. There are functions called Str and Int that are for these purposes alone.

So when you try to use something like

//
var myNumber = Int("5")

you get a compiler warning and it does not work, because there is no function that takes a string and converts it to Int . So how do you work with this? How do you convert a String into an Int ? is it not possible?

There is a function that is part of the Swift String class, it is called toInt . This can be used to convert a String to an Int . There is no other function to convert it to a decimal either a float or a double.

That is fine, the return type of this function is Int? (Optional Int), what if you wanted to use this in your program where you simply wanted to cast it using the Int(stringNumber) and expect an Int , not an Int? .

It’s simple, you can create an extension as follows

//
extension Int {
    init(_ theString: String){
        if let res = theString.toInt() {
            self = res
        } else {
            self = 0 //Int.min
        }
    }
}

var five = Int("5")
var fifty = Int("50a")

I have used a 0 instead of Int.min because in some cases you just want a 0 as the value of a non numeric string. That’s all there is to adding the missing functionality to the Int structure.

Views All Time
Views All Time
1269
Views Today
Views Today
2
Posted in Basics, Tip, Tutorial and tagged , , , , , , .

Leave a Reply

Your email address will not be published.