[SOLVED] How do I get part of a string in swift?

Issue

I would like to find out how to get a part of a string in Swift. I am looking for the Swift equivalents of the Mid$, Right$, and Left$ functions. Any help would be appreciated.

Solution

Edit: This answer was from 2014 and is obsolete today, I recommend referencing Vyacheslav’s answer instead

The equivalent of Left is substringToIndex

Example: (directly from this site)

let myString = "ABCDEFGHI"
let mySubstring = (myString.substringToIndex(2))
//This grabs the first 2 digits of the string and stops there,
//which returns "AB"

The (rough) equivalent of Right is substringFromIndex

Example: (directly from the same site)

let myString = "ABCDEFGHI"
let mySubstring = (myString.substringFromIndex(2))
//This jumps over the first 2 digits of the string and grabs the rest,
//which returns "CDEFGHI"

See https://web.archive.org/web/20170504165315/http://www.learnswiftonline.com/reference-guides/string-reference-guide-for-swift/

Answered By – Nick Meyer

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *