user2924482
user2924482

Reputation: 9120

Swift 3: stringByReplacingCharactersInRange alternatives

Any of you knows an stringByReplacingCharactersInRange to be use in Swift 3?

I'm trying to convert this Objective-C to Swift:

strToSort = [strToSort stringByReplacingCharactersInRange:NSMakeRange((i-1),1) withString: [strToSort substringWithRange:NSMakeRange((i),1)]];

I'll really appreciate your help.

Upvotes: 2

Views: 3945

Answers (2)

Nirav D
Nirav D

Reputation: 72410

In Swift 3 it is.

strToSort = strToSort.replacingCharacters(in: range, with: str)

Note: Here range is type of Swift Range<String.Index> object not NSRange.

For more details on Range check Apple Documentation.

Ex:

let str = "Apple"
let i = 3
let range = str.index(str.startIndex, offsetBy: i-1)..<str.index(str.startIndex, offsetBy: i)
let subStringRange = str.index(str.startIndex, offsetBy: i)..<str.index(str.startIndex, offsetBy: i+1)
print(str.replacingCharacters(in: range, with: str.substring(with: subStringRange)))

Output:

Aplle

Upvotes: 8

Ti3t
Ti3t

Reputation: 266

quick way, using NSString

let strToSort: NSString = "string to sort" let newString = strToSort.replacingCharacters(in: NSMakeRange(0, 6), with: "") print(newString) // to sort

Hope it helps

Upvotes: 0

Related Questions