How to use deleteCharactersInRange?

I want to call the "deleteCharactersInRange" method, but it does not work.

This is an excerpt from the documentation for apples:

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' has no member named 'deleteCharactersInRange'

+4
source share
3 answers

The method you are quoting refers to NSMutableString . But since you use Swift and have not explicitly created it, you get Swift String.

If you want to work with Swift String, you need to use str.removeRangeand it is rather inconvenient to use Range:

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

DarkDust Swift extension, removeRange:

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

:

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

Swift 3

Swift 3 requires the use of range operators a..<bor 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))
+3
source

All Articles