Stats

Contributors: 1
2016-04-14
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook

Convert numbers to/from strings

Download swift eBook

Example

Use String initializers for converting numbers into strings:

String(1635999)                              // returns "1635999"
String(1635999, radix: 10)                   // returns "1635999"
String(1635999, radix: 2)                    // returns "110001111011010011111"
String(1635999, radix: 16)                   // returns "18f69f"
String(1635999, radix: 16, uppercase: true)  // returns "18F69F"
String(1635999, radix: 17)                   // returns "129gf4"
String(1635999, radix: 36)                   // returns "z2cf"

Or use string interpolation for simple cases:

let x = 42, y = 9001
"Between \(x) and \(y)"  // equivalent to "Between 42 and 9001"

Use initializers of numeric types to convert strings into numbers:

if let num = Int("42") { /* ... */ }                // num is 42
if let num = Int("Z2cF") { /* ... */ }              // returns nil (not a number)
if let num = Int("z2cf", radix: 36) { /* ... */ }   // num is 1635999
if let num = Int("Z2cF", radix: 36) { /* ... */ }   // num is 1635999
if let num = Int8("Z2cF", radix: 36) { /* ... */ }  // returns nil (too large for Int8)