Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSAttributedStringKey error with swift 4

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.

like image 928
j.doe Avatar asked Jan 18 '18 12:01

j.doe


2 Answers

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

like image 80
Krunal Avatar answered Sep 17 '22 15:09

Krunal


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.

like image 44
Milan Nosáľ Avatar answered Sep 20 '22 15:09

Milan Nosáľ