8

After updating to Swift 4 I am getting an error on this code

    attributes["NSFont"] = font
    attributes["NSColor"] = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1)

Cannot subscript a value of type '[NSAttributedStringKey : Any]' with an index of type 'String'

I was able to fix the first line by replacing ["NSFont"] with NSAttributedStringKey.font but I am not sure how to fix the second one.

Krunal
  • 77,632
  • 48
  • 245
  • 261
j.doe
  • 4,559
  • 6
  • 20
  • 31
  • NSAttributedStringKey.backgroundColor ,NSAttributedStringKey.foregroundColor – Dixit Akabari Jan 18 '18 at 12:57
  • `attributes["NSFont"]` That's a not recommended way to do so. Use `NSFontAttributeName` and `NSForegroundColorAttributeName` for the other one. What if tomorrow iOS SDK decided that instead of `NSFont` for the value it would be `UIFont` (which seems more "iOS")? That's why at first place that code is not recommended. Then with Swift 4, use the `NSAttributedStringKey` correspondant. – Larme Jan 18 '18 at 12:57

3 Answers3

19

In swift 4 - NSAttributedString representation is completely changed.

Replace your attribute dictionary - attributes type, from [String : Any] to [NSAttributedStringKey : Any] or [NSAttributedString.Key : Any], if you've not done.

Try this in

Swift 4.2+:

attributes[NSAttributedString.Key.font] = font
attributes[NSAttributedString.Key.foregroundColor] = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1)

Swift 4.0 & 4.1:

attributes[NSAttributedStringKey.font] = font
attributes[NSAttributedStringKey.foregroundColor] = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1)

Here is note from Apple document: NSAttributedString.Key

Krunal
  • 77,632
  • 48
  • 245
  • 261
3

Use NSAttributedStringKey.foregroundColor for the second one, keys are not Strings anymore, but enum constants.

attributes[NSAttributedStringKey.font] = font
attributes[NSAttributedStringKey.foregroundColor] = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1)

You can find all the keys in the official docs for NSAttributedStringKey.

Milan Nosáľ
  • 19,169
  • 4
  • 55
  • 90
1

For Swift 3.3, NSForegroundColorAttributeName, NSFontAttributeName like

NSAttributedString(string: "text", attributes: [NSForegroundColorAttributeName : UIColor.white])

For Swift 4.0+

NSAttributedString(string: "text", attributes: [NSAttributedStringKey.foregroundColor : UIColor.white])
Bhanu
  • 1,249
  • 10
  • 17