Skip to main content
9 of 9
Added a "Swift 2" heading.
Adil Hussain
  • 32.6k
  • 24
  • 127
  • 170

Swift 2:

A solution is substringFromIndex

let a = "StackOverFlow" let last4 = a.substringFromIndex(a.endIndex.advancedBy(-4)) 

or suffix on characters

let last4 = String(a.characters.suffix(4)) 

Swift 3:

In Swift 3 the syntax for the first solution has been changed to

let last4 = a.substring(from:a.index(a.endIndex, offsetBy: -4)) 

Swift 4+:

In Swift 4 it becomes more convenient:

let last4 = a.suffix(4) 

The type of the result is a new type Substring which behaves as a String in many cases. However if the substring is supposed to leave the scope where it's created in you have to create a new String instance.

let last4 = String(a.suffix(4)) 
vadian
  • 286.2k
  • 32
  • 378
  • 379