Xcode 6.1 Swift中的属性字典

时间:2014-09-22 11:50:09

标签: xcode swift

从Xcode 6 Beta 7升级到Xcode 6.1 Beta 2后,以下内容不再有效:

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

我试过将字典声明为

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

但我收到错误"无法转换...'字典'到#NSString!'"。将密钥声明为NSString!而不是NSString会抱怨NSString!无法播放。有线索吗?

1 个答案:

答案 0 :(得分:18)

排序。像往常一样,实际的错误是红鲱鱼。 UIFont(name: , size:)现在有一个init?初始化程序,因此是可选的。现在正确使用:

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

或更准确地说:

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