13

It works fine to cast a Swift String as an NSString.

let string = "some text"
let nsString = string as NSString

But when I do

let string = "some text"
let nsMutableString = string as NSMutableString

I get the error

'String' is not convertible to 'NSMutableString'

How to I convert it?

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393

2 Answers2

26

You cannot cast a String as an NSMutableString, but you can use an NSMutableString initializer.

let string = "some text"
let nsMutableString = NSMutableString(string: string)
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
1

I tried your code it shows error

   'NSString' is not a subtype of 'NSMutableString'

If you want to convert string to NSMutableString in swift by simply constructing it with NSMutableString(string: ...)

   let string = "some text"
   let nsMutableString = NSMutableString(string: string)

Above code works fine.

user3182143
  • 9,459
  • 3
  • 32
  • 39