Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xcode 6.1 Attribute Dictionaries in Swift

Tags:

xcode

swift

After upgrading to Xcode 6.1 Beta 2 from Xcode 6 Beta 7, the following no longer works:

let font = UIFont(name: "Arial", size: 16)
let colour = UIColor.redColor()
let attributes = [NSFontAttributeName: font, NSForegroundColorAttributeName: colour]

I have tried specifically declaring the dictionary as

let attributes: [NSString : AnyObject] = [NSFontAttributeName: font, NSForegroundColorAttributeName: colour]

but I am receiving the error "Cannot convert ... 'Dictionary' to 'NSString!'". Declaring the key as NSString! rather than NSString complains that NSString! is not hashable. Any clues?

like image 371
Grimxn Avatar asked Sep 22 '14 11:09

Grimxn


1 Answers

Sorted. As usual, the actual error is a red herring. UIFont(name: , size:) now has an init? initialiser, and so is optional. Correct usage is now :

let font = UIFont(name: "Arial", size: 16)! // Unwrapped
let colour = UIColor.redColor()
let attributes: [NSString : AnyObject] = [NSFontAttributeName: font, NSForegroundColorAttributeName: colour]

or, more correctly:

if let font = UIFont(name: "Arial", size: 16) {
    let colour = UIColor.redColor()
    let attributes: [NSString : AnyObject] = [NSFontAttributeName: font, NSForegroundColorAttributeName: colour]
    // ...
}
like image 104
Grimxn Avatar answered Oct 02 '22 14:10

Grimxn