我无法解决这个错误。当我运行这个函数时,我收到一个 fatal error 。 fatal error :在解包可选值时意外发现 nil 下面是函数:
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
}
最佳答案
在所有行中都是这样的:
var currentFont : UIFont = currentAttributesDict.objectForKey(NSFontAttributeName) as UIFont
您正在从字典中提取一个值并进行显式转换(在本例中为 UIFont
)。
由于以下任何原因,所有这些行都可能失败:
- 字典中不存在指定的键,所以
objectForKey
返回nil
,转换失败 - 该值存在,但它不是您要将其转换为的类型,因此转换失败
我不知道您将如何使用所有这些变量,因此我无法提供最能解决您问题的正确答案。
但是,您可以通过使用可选的转换来摆脱运行时异常,将 as
替换为 as?
。请注意,它会将所有表达式结果转换为可选值,因此例如在上面的代码行中,当前字体将是 UIFont?
类型:
var currentFont : UIFont? = currentAttributesDict.objectForKey(NSFontAttributeName) as? UIFont
如何处理所有这些可选变量取决于您:您可以使用可选绑定(bind)(但我希望有大量嵌套的 if
),或者如果可能的话,将它们用作可选变量。
关于ios - 从 NSMutableString 解包 Optional 值时意外发现 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26736944/