Generics in Cocoa and half-way bridging

The NSAttributedString(string:attributes:) constructor has been updated with generics in Swift 2.0 so that the attributes parameter is of the type [String : AnyObject]?


However, this means that the following code doesn't work anymore:


        let font = CTFontCreateWithName("Monaco", 10, nil)
        let string = NSAttributedString(string: "foo", attributes: [kCTFontAttributeName : font])


The problem here is that kCTFontAttributeName has the type CFString, which is not automatically bridged to String, even though it's going to be immediately converted back to a CFString.


The workaround is to convert it manually:


        let font = CTFontCreateWithName("Monaco", 10, nil)
        let string = NSAttributedString(string: "foo", attributes: [String(kCTFontAttributeName) : font])

I ran into a similar, but different issue.


Consider the following:


var fontAttributes: [NSObject: AnyObject] = [NSObject: AnyObject]()
fontAttributes[NSFontNameAttribute] = titleFont
fontAttributes[NSParagraphStyleAttributeName] = titleStyle


Does not work.


var fontAttributes: [NSObject: AnyObject] = [NSObject: AnyObject]()
fontAttributes[String(kCTFontAttributeName)] = titleFont
fontAttributes[NSParagraphStyleAttributeName] = titleStyle


But this will.


It seems like something bad happened with the constructor change mentioned by the OP above and caused me a few days of frustration (Obj-C works as intended, however).


Edit: Be sure to use NSFontAttributeName instead of NSFontNameAttribute if setting a NSFont object into the dict.

You could use


let font = UIFont(name:"Monaco", size:10)
let string = NSAttributedString(string:"foo",attributes:[NSFontAttributeName: font])


(On OSX replace UIFont with NSFont)

Rod

Ahh. So I was using the wrong key in the dictionary. 😮 Was using: NSFontNameAttribute, should have been using: NSFontAttributeName.


What a dumb mistake on my end... Even worse when I consider that I used the correct key in the Obj-C version I made.

Generics in Cocoa and half-way bridging
 
 
Q