Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Build an Interactive Story App with Swift Creating the User Interface Programmatically Attributed Strings

Wing Sun Cheung
Wing Sun Cheung
4,933 Points

The store property of attributedText is NOT a type NSMutableAttributedString

Hi team,

I am really confused here. Inside of UILabel class, there is a property called:

var attributedText: NSAttributedString?

In the video, Pasan did this:

let attributedString = NSMutableAttributedString(string: page.story.text)
storyLabel.attributedText = attributedString

How is this possible? what I am confused about is var attributedText accepts only NSAttributedString, but somehow it also accepts NSMutableAttributedString?

Is it because since NSMutableAttributedString inherits from NSAttributedString, that makes NSMutableAttributedString equal to NSAttributedString?

thanks

2 Answers

Lone Nielsen
Lone Nielsen
13,764 Points

This here is the right answer

attributedString.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, attributedString.length))

almost nailed it, missing dot before the Key, or at least for Xcode 10.2.1 this is the right solution for the attributedString:

attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, attributedString.length))

Ashwin Iyer
Ashwin Iyer
11,684 Points

Hey so if you go back to around 1:40 in the video, he explains it better. But essentially, in objective C you need to use mutable types to be able to modify the objects. If we were to simply use NSAttributedString when we were changing the attributes, we would not be allowed to since the type is non-mutable.