2

I am trying to simply convert a character or string to an integer in Swift 3. I am a long time C++ developer who is just learning Swift and finding it extremely frustrating to do some of the simplest things in Swift 3 (ie, indexing into a string, converting a character to an int).

Can someone please help me convert characters to ints, specifically in Swift 3 Xcode 8?

Thank you!

2 Answers2

4

It's as simple as this.

let myString = "5"
let sum = 3 +  Int(myString)!  // Produces 8
print(Int(myString)!)

Indexing

let str = "My test String Index"
let index = str.index(str.startIndex, offsetBy: 4)
str[index] // Returns e from test

let endIndex = str.index(str.endIndex, offsetBy:-2)
str[Range(index ..< endIndex)] // returns String "est String Ind"

str.substring(from: index) // returns String "est String Index"
str.substring(to: index) // returns String "My t"
Declan McKenna
  • 4,321
  • 6
  • 54
  • 72
MwcsMac
  • 6,810
  • 5
  • 32
  • 52
1
let string = "1"
if let integer = Int(string) {
    print(integer)
}
R0CKSTAR
  • 118
  • 7