2014-11-04 67 views
0

我无法绕过这个错误。当我运行这个函数时,我得到一个致命的错误。致命错误:意外发现零而展开的可选值低于 的功能是:意外地发现零,而从NSMutableString解包可选值

func changeSelectedFontColor(fontColor: UIColor) { 

    let selectedRange : NSRange = self.textView.selectedRange 

    var currentAttributesDict : NSDictionary = textView.textStorage.attributesAtIndex(selectedRange.location, effectiveRange: nil) 

    var currentFont : UIFont = currentAttributesDict.objectForKey(NSFontAttributeName) as UIFont 

    let italFont = [NSFontAttributeName:UIFont(name: "Georgia-Italic", size: 18.0)] 

    var currentColor : UIColor = currentAttributesDict.objectForKey(NSForegroundColorAttributeName) as UIColor 

    var currentBGColor : UIColor = currentAttributesDict.objectForKey(NSBackgroundColorAttributeName) as UIColor 

    var currentUnderlinedText : UIFont = currentAttributesDict.objectForKey(NSUnderlineStyleAttributeName) as UIFont 

    var currentparagraphStyle : NSMutableParagraphStyle = currentAttributesDict.objectForKey(NSParagraphStyleAttributeName) as NSMutableParagraphStyle 
} 

回答

1

在这样的所有行:

var currentFont : UIFont = currentAttributesDict.objectForKey(NSFontAttributeName) as UIFont 

你提取字典的价值,做一个明确的投(在这种情况下为UIFont)。 所有这些线可能会因任何原因如下:

  • 指定的键不存在于字典,所以objectForKey回报nil,并转换失败
  • 的价值存在,但它不是因此投射失败

我不知道如何使用所有这些变量,因此我无法提供最佳解决问题的正确答案。

但是,您可以使用可选的强制转换来取消运行时异常,用as?代替as。请注意,它会变成所有的表达式的结果为选配,因此,例如在上面的代码行,当前字体将UIFont?类型:

var currentFont : UIFont? = currentAttributesDict.objectForKey(NSFontAttributeName) as? UIFont 

做什么用的所有这些可选的变量是给你:你可以使用可选的绑定(但我期望有大量的嵌套if),或者如果可能的话,只是将它们用作可选项。

+0

我正在构建一个文本编辑器,并使用这些变量来检查是否已经对所选文本进行了一些格式更改。如果有的话,我可以将它们添加到当前的更改中。例如,可能选中的文本带下划线,我稍后想要更改文本的颜色。我需要检查下划线属性是否已设置,然后将其添加到属性字符串以及新更改,以便所有更改都会保留。我希望我解释得很好。 – LearningGuy 2014-11-07 14:10:30

+0

在这种情况下,对于每个变量,您应该使用[可选绑定](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097 -CH5-XID_503)来检查一个值是否不为零,并根据需要做任何事情 – Antonio 2014-11-07 14:32:34

0

ObjectForKey将返回一个可选项,您应该使用as?将其转换为可选项并检查其值。

let value = dict.objectForKey("hello") as? String 

值是可选的,你可以做

if value == nil {} 

或者

if let value = dict.objectForKey("hello") as? String { 

} 
0

你是不是测试的nilobjectForKey(_:)返回一个可选项,您强制展开(使用as),因此如果objectForKey(_:)返回nil,那么您会崩溃。

您可以使用as?

var currentColor: UIColor? currentAttributesDict[NSForegroundColorAttributeName] as? UIColor 

保持值作为选配,也可以提供使用??运营商的默认值。

var currentColor: UIColor currentAttributesDict[NSForegroundColorAttributeName] as? UIColor ?? UIColor.blackColor() 

注:而不是使用objectForKey(_:),您可以使用[]。我认为它更好。

相关问题