How to use deleteCharactersInRange?

5.9k views Asked by At

I want do call the method "deleteCharactersInRange" but it doesn't work.

This is an excerpt from Apples Documentation:

Swift

func deleteCharactersInRange(_ aRange: NSRange)

    var day = ""

    let stringRange:NSRange = NSMakeRange(0, 4)
    day = day.deleteCharacterInRange(stringRange)


    // I've also tried this, because in the Documentation 
    // I can't see wether the method is void or returns a String

    day.deleteCharacterInRange(stringRange)

I get this error message:

'String' does not have a member named 'deleteCharactersInRange'

3

There are 3 answers

10
DarkDust On BEST ANSWER

The method you're citing belongs to NSMutableString. But since you're using Swift and haven't explicitly created one, you get a Swift String.

If you want to operate on Swift String, you need to use str.removeRange and the rather awkward to use Range:

var str = "Hello, playground"
str.removeRange(Range<String.Index>(start: str.startIndex, end:advance(str.startIndex, 7)))
// "playground"
6
nhgrif On

In light of DarkDust's answer, we can make a very Swift-like extension that will make removeRange easier to use:

extension String {
    mutating func deleteCharactersInRange(range: NSRange) {
        let startIndex = self.startIndex.advancedBy(range.location)
        let length = range.length
        self.removeRange(startIndex ..< startIndex.advancedBy(length))
    }
}

Now you can use it as such:

let range = NSMakeRange(0,4)
var day = "Tuesday"
day.deleteCharactersInRange(range) // day = "day"
0
ff10 On

Update for Swift 3

In Swift 3 it is required to use the range operators a..<b or a...b.

var aString = "This is just the beginning"
str.removeRange(Range<String.Index>(str.startIndex ..< str.startIndex.advancedBy(10)))

or even more concise

aString.removeRange(aString.startIndex..<aString.startIndex.advancedBy(10))