Cannot call "index" with list type argument (string: NSString, attributes: [NSString: UIFont?])

I have the following code, but when I compile I get this error:

"Unable to call subscript with argument list of type (string: NSString, attributes: [NSString: UIFont?])".

This code works fine on xCode 6.0.1 , but after upgrading to 6.1 it gives 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)

      

0


source to share


1 answer


Unfortunately, the error messages from Swift are sometimes not very helpful. The problem is not with the index, but with the array of attributes.

As you can see in the title, the UIFont initializer you are using returns an optional UIFont:

init?(name fontName: String, size fontSize: CGFloat) -> UIFont

      

But the NSAttributedString

initializer expects an array [NSObject : AnyObject]

. Please note AnyObject

, this is not AnyObject?

. So you need to deploy first UIFont

.

You have two options:



Safe way. Check if these UIFonts can be generated, otherwise use the 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)]

      

A dangerous path. Wind up additional fonts. This will crash if the font cannot be built:

let textboldFont = [NSFontAttributeName:UIFont(name: "ProximaNova-Bold", size: 15.0)!]
let textregularFont = [NSFontAttributeName:UIFont(name: "ProximaNova-Regular", size: 15.0)!]

      

+1


source







All Articles