fullMoon February 2016

Swift 2, convert a String into an Int

I'm using Xcode 7 Beta 3 and reading through Swift 2.2 document. I'm trying to compile this example found in the Basics section of the document:

let possibleNumber = "123"
let convertedNumber = Int(possibleNumber)

It is supposed to convert a string into an optional int. However Xcode gives the error:

Cannot call value of non-function type 'int'

I was working on Xcode 7.2.1, then I knew that Swift 2.2 is packaged with Xcode 7.3 Beta 3, so I downloaded that to try, but the same error happens. So, is the document wrong? and how to achieve the string into int conversion?

Answers


Brian Ogden February 2016

There is nothing wrong with your code, I tested and ran your exact code in Xcode 7.2:

let possibleNumber = "123"
let convertedNumber = Int(possibleNumber)
print("\(convertedNumber)")

It complied, ran within an app of mine, and printed the Int value 123.

Perhaps the error is being thrown from another area of code in your Xcode app, other then the code you think is throwing the error....

Perhaps you are not referencing the version of Swift you think you are...

Note, you should use if let with any conversion attempt:

if let convertedNumber = Int(possibleNumber) {
}

The if let should be used for a conversion no matter how remote the possibility of failure.

Post Status

Asked in February 2016
Viewed 2,768 times
Voted 8
Answered 1 times

Search




Leave an answer