Swift 4 无法转换“[String : AnyObject]"类型的值?到预期的参数类型 '[NSAttributedStringKey : Any]?' [英] Swift 4 Cannot convert value of type '[String : AnyObject]?' to expected argument type '[NSAttributedStringKey : Any]?'

查看:25
本文介绍了Swift 4 无法转换“[String : AnyObject]"类型的值?到预期的参数类型 '[NSAttributedStringKey : Any]?'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚更新到 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]

这篇关于Swift 4 无法转换“[String : AnyObject]"类型的值?到预期的参数类型 '[NSAttributedStringKey : Any]?'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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