twigofa twigofa - 5 months ago 39
Swift Question

How to get last 4 characters of a string?

I need to seperate the last 4 letters of a string. How can I seperate it? The length of string is changing.

Ex:

var a = "StackOverFlow"
var last4 = a.lastFour //That's what I want to do
print(last4) //prints Flow

Answer

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))

code is Swift 2

Comments