Search code examples
iosswift3

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?


Solution

  • 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.