简体   繁体   English

Xcode 6.1 Swift中的属性字典

[英]Xcode 6.1 Attribute Dictionaries in Swift

After upgrading to Xcode 6.1 Beta 2 from Xcode 6 Beta 7, the following no longer works: 从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]

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!'". 但我收到错误“无法转换...'字典'到'NSString!'”。 Declaring the key as NSString! 将密钥声明为NSString! rather than NSString complains that NSString! 而不是NSString抱怨NSString! is not hashable. 不耐用。 Any clues? 有线索吗?

Sorted. 排序。 As usual, the actual error is a red herring. 像往常一样,实际的错误是红鲱鱼。 UIFont(name: , size:) now has an init? UIFont(name: , size:)现在有一个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]
    // ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM