Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 902
Don Miguel Avatar asked Dec 27 '25 14:12

Don Miguel


2 Answers

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
like image 186
Xcoder Avatar answered Dec 31 '25 17:12

Xcoder


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.

like image 43
vadian Avatar answered Dec 31 '25 17:12

vadian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!