This question already has an answer here:
-
NSFontAttributedString worked before XCode 6.1
2 answers
I have the following code but when I compile I'm getting this error:
"Cannot invoke 'subscript' with an argument list of type '(string: NSString, attributes: [NSString : UIFont?])".
This code is working fine on xCode 6.0.1 but after after upgrading to 6.1 it is giving this error.
let textboldFont = [NSFontAttributeName:UIFont(name: "ProximaNova-Bold", size: 15.0)]
let textregularFont = [NSFontAttributeName:UIFont(name: "ProximaNova-Regular", size: 15.0)]
let para = NSMutableAttributedString()
let attributedstring1 = NSAttributedString(string: dateArray[1] as NSString, attributes:textboldFont)
Unfortunately the error messages from Swift are sometimes not really helpful. The problem is not the subscript, it's the attributes array.
As you can see in the header the UIFont initializer you use returns an optional UIFont:
init?(name fontName: String, size fontSize: CGFloat) -> UIFont
But NSAttributedString
initializer expects an [NSObject : AnyObject]
array. Note the AnyObject
, it's not AnyObject?
. So you have to unwrap the UIFont
first.
You have two options:
The safe way. Check if those UIFonts could be created, otherwise use system supplied font:
let textboldFont = [NSFontAttributeName:UIFont(name: "ProximaNova-Bold", size: 15.0) ?? UIFont.boldSystemFontOfSize(15.0)]
let textregularFont = [NSFontAttributeName:UIFont(name: "ProximaNova-Regular", size: 15.0) ?? UIFont.systemFontOfSize(15.0)]
The dangerous way. Forcefully unwrap the optional fonts. This will crash if the font could not be created:
let textboldFont = [NSFontAttributeName:UIFont(name: "ProximaNova-Bold", size: 15.0)!]
let textregularFont = [NSFontAttributeName:UIFont(name: "ProximaNova-Regular", size: 15.0)!]