4

I know we can use subscript to cut a part of the string in Swift 4, .

let s = "aString"
let subS = s[..<s.endIndex]

But the problem is, how to cut the s to a subString like aStr.
I mean, What I want to do is something like s[..<(s.endIndex-3)].
But it's not right.
So, how to do it in Swift 4.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
JsW
  • 1,682
  • 3
  • 22
  • 34

3 Answers3

17

String.Index is not an integer, and you cannot simply subtract s.endIndex - 3, as "Collections move their index", see A New Model for Collections and Indices on Swift evolution.

Care must be taken not to move the index not beyond the valid bounds. Example:

let s = "aString"

if let upperBound = s.index(s.endIndex, offsetBy: -3, limitedBy: s.startIndex) {
    let subS = String(s[..<upperBound])
} else {
    print("too short")
}

Alternatively,

let upperBound = s.index(s.endIndex, offsetBy: -3, limitedBy: s.startIndex) ?? s.startIndex
let subS = String(s[..<upperBound])

which would print an empty string if s has less then 3 characters.

If you want the initial portion of a string then you can simply do

let subS = String(s.dropLast(3))

or as a mutating method:

var s = "aString"
s.removeLast(min(s.count, 3))
print(s) // "aStr"
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
2

As you said error is Binary operator '-' cannot be applied to operands of type 'String.Index' and 'Int'

You have to find the Swift.Index first.

let s = "aString"
let index = s.index(s.endIndex, offsetBy: -3)
let subS = s[..<index]
print(String(subS))
Bilal
  • 18,478
  • 8
  • 57
  • 72
  • 1
    This would crash if the original string has less than 3 characters. Better to use dropLast as proposed by Martin – Leo Dabus Jan 20 '18 at 07:43
2

All I wanted was a simple Substring, from the start, of x characters. Here's a function.

func SimpleSubstring(string : String, length : Int) -> String {
    var returnString = string

    if (string.count > length) {
        returnString = String(string[...string.index(string.startIndex, offsetBy: length - 1)])
    }

    return returnString
}

usage

let myTruncatedString : String = SimpleSubstring(string: myBigString, length: 10)
Mike Irving
  • 1,480
  • 1
  • 12
  • 20