Swift 4 无法转换“[String : AnyObject]"类型的值?到预期的参数类型 '[NSAttributedStringKey : Any]?'

Swift 4 无法转换“[String : AnyObject]

问题描述:

我刚刚更新到 Xcode 9 并将我的应用程序从 swift 3 转换为 swift 4.我有使用字符串来标记轴和其他变量的图表.所以我有一个 moneyAxisString = "Money".以前我可以使用以下代码绘制它们:

I have just updated to Xcode 9 and converted my app from swift 3 to swift 4. I have graphs which use strings to label the axes and other variables. So I have a moneyAxisString = "Money". Previously I was able to draw them using this code:

moneyAxisString.draw(in: CGRect(x: CGFloat(coordinateXOriginLT + axisLength/3), y: CGFloat(coordinateYOriginRT + axisLength + 5 * unitDim), width: CGFloat(300 * unitDim), height: CGFloat(100 * unitDim)), withAttributes: attributes as? [String : AnyObject])

其中attributes是字典,定义如下

Where attributes is a dictionary defined as follows

 attributes = [
        NSAttributedStringKey.foregroundColor: fieldColor,
        NSAttributedStringKey.font: fieldFont!,
        NSAttributedStringKey.paragraphStyle: style

    ]

现在我的应用程序无法编译,我收到消息:

Now my app won't compile and I am getting the message:

无法转换[String : AnyObject]"类型的值?到预期的参数类型 '[NSAttributedStringKey : Any]?'

Cannot convert value of type '[String : AnyObject]?' to expected argument type '[NSAttributedStringKey : Any]?'

It's a type mismatch: [String : AnyObject] 显然不是 [NSAttributedStringKey : Any]

It's a type mismatch: [String : AnyObject] is clearly not [NSAttributedStringKey : Any]

⌥-单击 NSAttributedStringKey 以查看声明.

解决办法是将attributes声明为

var attributes = [NSAttributedStringKey : Any]()

去除下垂

 ..., withAttributes: attributes)

简单地写

attributes = [.foregroundColor: fieldColor,
              .font: fieldFont!,
              .paragraphStyle: style]