twigofa twigofa - 2 years ago 161
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.


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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download