51

I have a NSMutableAttributedString and want to convert it back into a simple String.

var attributedString = NSMutableAttributedString(string: "hello w0rld")

How can I get just the String out of a NSMutableAttributedString the easiest?

ixany
  • 5,433
  • 9
  • 41
  • 65

3 Answers3

131

Use the string property on NSMutableAttributedString:

var attributedString = NSMutableAttributedString(string: "hello, world!")
var s = attributedString.string
jtbandes
  • 115,675
  • 35
  • 233
  • 266
mipadi
  • 398,885
  • 90
  • 523
  • 479
  • 7
    @Julian: Well, yes, an `NSString` doesn't have any attributes. – mipadi Aug 13 '15 at 16:28
  • Right, but the NSAttributedString does. I was hoping that the attributes would be rendered along with the string. You know what I mean? otherwise these get lost. – Julian B. Aug 13 '15 at 16:39
  • 2
    @Julian: In that case, you wouldn't bother converting to `NSString`. – mipadi Aug 13 '15 at 16:45
  • There are things are simpler with regular strings like adjusting the text to fit a frame, or replacing the text of label. Additionally, it is less expensive to use strings if you are manipulating the text frequently. So this is why I would bother converting it. – Julian B. Aug 13 '15 at 16:54
  • @JulianB. if you want a normal string with attributes conserved, use String(yourAttributedString) – Guy Oct 04 '16 at 14:16
  • 2
    The `string` property returns a `String` object, not an `NSString` object. – ThomasW Apr 16 '18 at 04:15
6

If you strictly want an NSString, not a String use the following:

let s = attributedString.string as NSString
ThomasW
  • 16,981
  • 4
  • 79
  • 106
  • This answer has already given by `mipadi`. OP asked for `NSString` because question is old and at that time `Swift` had `NSString` not `String`. So nowadays probably nobody would like to get `NSString` from `NSMutableAttributedString`. – TheTiger Apr 16 '18 at 05:06
  • @TheTiger There are still cases where you might specifically want an `NSString` instead of a `String`. In particular, if you need to use an `NSRange` from the string. `NSRange` is not compatible with `Range`. – ThomasW Apr 16 '18 at 05:09
  • Still in 2018 it is very basic to convert `String` into `NSString`. – TheTiger Apr 16 '18 at 05:18
  • 1
    Sure, it is basic, but some people don't know and if you Google this is the first answer that comes up, so for some people this might be helpful. – ThomasW Apr 16 '18 at 07:03
2

if you want to keep the atributted string simply use yourLabel.attributedText = atributedTtext

TheTiger
  • 13,264
  • 3
  • 57
  • 82