Don Miguel
Don Miguel

Reputation: 912

Get String from NSMutableString in swift

What's the proper way of getting a String from a NSMutableString? I am currently using:

var mutableString = NSMutableString(string: string)
var string = mutableString.substring(from: 0)

which seems a bit hackish...

Thanks

Upvotes: 3

Views: 3417

Answers (3)

vadian
vadian

Reputation: 285270

As already mentioned in the comments the proper way is not to use NSMutableString at all.

Your given example

let mutableString = NSMutableString(string: "Hello World")
mutableString.replaceCharacters(in: NSRange(location: 4, length: 5), with: "XXXXX")
let swiftString = String(mutableString)

can be written in native Swift

var string = "Hello World"

let nsRange = NSRange(location: 4, length: 5)
string.replaceSubrange(Range(nsRange, in: string)!, with: "XXXXX")

Same result but the latter is more efficient.

Upvotes: 1

Xcoder
Xcoder

Reputation: 1453

Just cast the NSMutableString as String:

var mutableString = NSMutableString(string: "Example")
var string = String(mutableString)

Or:

var mutableString = NSMutableString(string: "Example")
var string = mutableString as String

Upvotes: 4

Nikola Ristic
Nikola Ristic

Reputation: 449

This should do the trick:

let newStr = String(mutableString)

Upvotes: 0

Related Questions