NSAttributedString.Key in IOS

I am trying to define attibutes for Strings, with the following statement (IOS app)


var attributes = [NSAttributedString.Key: Any]() 
attributes[NSAttributedString.Key.foregroundColor] = newColor

I get a compiler error :

Type 'NSAttributedString.Key' (aka 'NSString') has no member 'foregroundColor'

even though the constant is defined in doc


So I change to

attributes[NSForegroundColorAttributeName] = newColor


Get another error:

Cannot subscript a value of type '[NSAttributedString.Key : Any]' (aka 'Dictionary<NSString, Any>') with an index of type 'String'


Which is bizarre again, as when I test (option-click in attribute name) the type of NSForegroundColorAttributeName, I get

static let foregroundColor: NSAttributedString.Key


I finally change to:

attributes[NSForegroundColorAttributeName as NSAttributedString.Key] = newColor

which works.


Am I missing something or is this a bit messy ?

Accepted Reply

I cannot reproduce the same issue with Xcode 10.2 (Swift Language Version set to Swift 5).


Which version of Xcode are you using? How have you set Swift Language Version?

Or other settings or hidden code may be affecting.


Please create a minimum project to reproduce the issue, and show whole code and related settings.

Replies

I cannot reproduce the same issue with Xcode 10.2 (Swift Language Version set to Swift 5).


Which version of Xcode are you using? How have you set Swift Language Version?

Or other settings or hidden code may be affecting.


Please create a minimum project to reproduce the issue, and show whole code and related settings.

Sorry I did not tell.


In fact, I modified an older project (with XCode 10.1ß3), and did not notice it was defining Swift3 as language version.


Changed to 4.2 and solved the point.


With XCode 10.2, I had to set to Swift5 for the same code to compile.


Thanks for the help.