Stanley Stanley - 2 months ago 204
Swift Question

inout String is not convertible to String in Swift 3 range

I have the following code that works fine in Swift 2:

let myModifiedString = myOriginalString.replacingOccurrences(of: "#(?:\\S+)\\s?",
with: "",
options: .regularExpression,
range: Range(myOriginalString.characters.indices))


I am busy upgrading my code to Swift 3, however, and I get the error 'inout String' is not convertible to type 'String'.

The error occurs on myOriginalString.characters.indices.

I saw that Swift 3 made some changes to how ranges are implemented and also to some String functionality. I just can't seem to find a succinct solution to resolve the problem and convert this statement to proper Swift 3 syntax. What is the proper Swift 3 syntax for the statement?

Answer

In Swift 3, indices property has become a Collection of Index, and not any more a sort of Range. If you want a Range of Index representing the whole String, you need to write something like this:

let myModifiedString = myOriginalString.replacingOccurrences(of: "#(?:\\S+)\\s?",
                                                             with: "",
                                                             options: .regularExpression,
                                                             range: myOriginalString.startIndex..<myOriginalString.endIndex)