1
votes

I'm trying to replace a substring with another substring but I'm getting this error:

 cannot convert value of type 'String.Index' (aka 'String.CharacterView.Index') to expected argument type 'Range<String.Index>' (aka 'Range<String.CharacterView.Index>')

Here is my Code:

// This are the position of the substrings:
let rangeOne = strToSort.index(strToSort.startIndex, offsetBy: (i-1))
let rangeTwo = strToSort.index(strToSort.startIndex, offsetBy: (i))

Here is where I try to make the replacement:


strToSort = strToSort.replacingCharacters(in: rangeOne, with: strToSort.substring(with: rangeTwo))

But I'm getting this error:

enter image description here

Any of you knows what I'm doing wrong or a work around this?

I'll really appreciate your help

1
You want to change EHLLOAGAIN to HELLOAGAIN ?Nirav D
var chars = "EHLLOAGAIN".characters.map{String($0)} swap(&chars[0], &chars[1])Leo Dabus
@LeoDabus, but how you do it programmatically. what I mean is if switch substring in position x with substring at position y?user2924482

1 Answers

1
votes

Modify your code like this

var strToSort = "HELLOAGAIN"
let rangeOne = strToSort.index(strToSort.startIndex, offsetBy: (2))
let rangeTwo = strToSort.index(strToSort.startIndex, offsetBy: (3))
let stringRange = Range(uncheckedBounds: (lower: rangeOne, upper: rangeTwo))
strToSort = strToSort.replacingCharacters(in: stringRange, with: strToSort)
print(strToSort)

As in your code there is no range defined and the method replacingCharacters require argument of type Range<String.Index> and you are providing type String.Index is incorrect so you are getting error.

If you want to replace occurrences of string like H with E you can use different String method like

let aString: String = "HELLO"
let newString = aString.stringByReplacingOccurrencesOfString("H", withString: "E", options: NSStringCompareOptions.LiteralSearch, range: nil)