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.

8
  • Whats wrong in it? Commented Jan 20, 2018 at 7:27
  • For s[..<(s.endIndex-3)], the error is Binary operator '-' cannot be applied to operands of type 'String.Index' and 'Int' Commented Jan 20, 2018 at 7:30
  • Use can learn from here Commented Jan 20, 2018 at 7:35
  • 1
    @JsW stackoverflow.com/a/38215613/2303865 Commented Jan 20, 2018 at 8:01
  • 1
    and stackoverflow.com/questions/40028035/… Commented Jan 20, 2018 at 8:07

3 Answers 3

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" 
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

This would crash if the original string has less than 3 characters. Better to use dropLast as proposed by Martin
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) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.