Michel
Michel

Reputation: 11753

NSFontAttributeName vs NSAttributedStringKey.font

I am having some trouble with Swift code in a library I have been using for a while. It seems related to some kind of version conflict, but I am not sure.

Here is the code:

let attribMsg = NSAttributedString(string: msg,
                               attributes: [NSAttributedStringKey.font:UIFont.systemFont(ofSize: 23.0)])

Here is the error message I get from the compiler:

Type 'NSAttributedStringKey' (aka 'NSString') has no member 'font'
    Did you mean 'zone'?  Fix(button)

enter image description here

Using this code in different project I noticed that on some of them I do not get the error message and it all compiles without any problem.

I also noticed that if I replace the above code by the following:

let attribMsg = NSAttributedString(string: msg,
                               attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 23.0)])

The projects with a problem will work while the others(previously working) show this other message:

'NSFontAttributeName' has been renamed to 'NSAttributedStringKey.font'

enter image description here

In other words some projects work with one type of code and some others work with the other type.

Needless to say that I do not want to change the code each time I switch from one project to another.

The experiments I made changing the Deployment Target of the project do not seem to make much difference. So comes my question: What is the way to handle this issue?

Upvotes: 9

Views: 17133

Answers (2)

nathangitter
nathangitter

Reputation: 9777

The projects are probably in different versions of Swift.

In Swift 4, NSFontAttributeName has been replaced with NSAttributedStringKey.font.

In Swift 5, NSFontAttributeName has been replaced with NSAttributedString.Key.font.

Upvotes: 37

sanch
sanch

Reputation: 716

Swift 4.2

NSAttributedStringKey renamed NSAttributedString.Key. However for this particular issue you need to get the raw value so the solution would be NSAttributedString.Key.font.rawValue

Take a look here for an in-depth explanation: https://stackoverflow.com/a/46459315/2440997

Upvotes: 4

Related Questions