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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With