Reputation: 912
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
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
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