All of the following examples use

var str = "Hello, playground"

substring(to: String.Index)

This takes the substring from the beginning of the string to the specified index.

let index = str.index(str.startIndex, offsetBy: 5)
str.substring(to: index)  // Hello

If you don't understand String.Index, see my previous answer.

substring(from: String.Index)

This takes the substring from the specified index to the end of the string.

let index = str.index(str.startIndex, offsetBy: 7)
str.substring(from: index)  // playground

substring(with: Range)

This one just gives you a substring based on the Range you pass in. Once you have the range, it's easy. Although still not as convenient as the old NSRange, this is a definite improvement over Swift 2 ranges.

let start = str.index(str.startIndex, offsetBy: 7)
let end = str.index(str.endIndex, offsetBy: -6)
let range = start..<end

str.substring(with: range)  // play

Reference: how does string substring work in swift 3

results matching ""

    No results matching ""