try to convert string to integer

Hi all,
at first I'm a beginner with xcode.

When I try to convert a string to integer I got this error
message: cannot find 'int' in scope

code:
var cString = "123"
var nNumber = 0
nNumber = int(cString)

the same thing when I try to convert from integer to string

cString = string(nNumber)

... what can I do to fix this problem?
Swift uses case-sensitive identifiers. In Swift Standard Library, Int is defined, but int is not.
Change int to Int and string to String.
Take care though:
Code Block
nNumber = Int(cString)

returns an optional.
Should write for instance :
Code Block
nNumber = Int(cString) ?? 0


But
Code Block
cString = String(nNumber)

is not an optional.
Ok, this fix my first problem, thanks ...

code: 
var cString = "123"
var nNumber = 0
nNumber = Int(cString)

... but now the next problem follows ...

message : "Value of optional type 'Int?' must be unwrapped to a value of type 'Int'"
what does this mean and what must I do?



You should better learn how to format your code here in the dev forums. (Use the icon <>.)


Seems you have not read the Swift book yet.
Optional is one of the core concept in Swift language, so you should better learn it before writing codes in Swift.
(There are several parts written about Optionals.)

And one more thing you need to know is that Swift is a strongly typed language, meaning every variable has its own type.
With declaring a variable as in your code:
Code Block
var nNumber = 0

This is equivalent to:
Code Block
var nNumber: Int = 0

The variable has a type Int. But the type of expression is Optional<Int> (also written as Int?), as String to Int conversion may fail.

You need to decide what to do when cString cannot be interpreted as an Int.
If want to supply some default value, you can use nil-coalescing operator ??. (As shown in the Claude31's reply.)
Code Block
nNumber = Int(cString) ?? 0

The type of the expression Int(cString) ?? 0 is non-Optional Int and you can assign the value to the variable of type Int.


By the way, prefixed identifiers like cString or nNumber are not preferred in Swift. You should better be accustomed to the Swift way.
Did you read my answer ? I gave the solution:

Take care though:
Code Block
nNumber = Int(cString)

returns an optional.
Should write for instance :
Code Block
nNumber = Int(cString) ?? 0


But
Code Block
cString = String(nNumber)

is not an optional, so no need to unwrap.
Thanks all for your help !

I come from C++ and PHP ... and now I know, at first I have to read the book!
try to convert string to integer
 
 
Q