Swift 中的 Xcode 6.1 属性字典 [英] Xcode 6.1 Attribute Dictionaries in Swift

查看:28
本文介绍了Swift 中的 Xcode 6.1 属性字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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]

但我收到错误无法将......'字典'转换为'NSString!'".将密钥声明为 NSString! 而不是 NSString 会抱怨 NSString! 不可哈希.有什么线索吗?

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?

推荐答案

已排序.像往常一样,实际的错误是一个红鲱鱼.UIFont(name: , size:) 现在有一个 init? 初始化器,所以是可选的.现在正确的用法是:

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]

或者,更准确地说:

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

这篇关于Swift 中的 Xcode 6.1 属性字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆