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

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

问题描述

如何将 '[String : AnyObject]?' 类型的值转换为预期的参数类型 '[NSAttributedStringKey : Any]?'?

How to convert values of type '[String : AnyObject]?'to expected argument type '[NSAttributedStringKey : Any]?'?

open class func drawText(context: CGContext, text: String, point: CGPoint, 
align: NSTextAlignment, attributes: [String : AnyObject]?)
{
    var point = point

    if align == .center
    {
        point.x -= text.size(withAttributes: attributes).width / 2.0
    }
    else if align == .right
    {
        point.x -= text.size(withAttributes: attributes).width
    }

    NSUIGraphicsPushContext(context)

    (text as NSString).draw(at: point, withAttributes: attributes)

    NSUIGraphicsPopContext()
}

推荐答案

这是 Swift 4 的一个新特性.所有采用字符串标识符和/或字典键的 Cocoa 方法现在都有自己的键类型.这样做的原因是为了增加一点类型安全性——在旧制度中,可能会不小心错误地传递了一个 String 常量,该常量本打算与其他 API 一起使用,但现在在Swift 4,这会导致编译错误.

This is a new feature of Swift 4. All the Cocoa methods that take string identifiers and/or dictionary keys now have their own types for the keys. The reason for this is to add a bit of type safety—in the old regime, it was possible to accidentally pass a String constant by mistake that was meant to be used with some other API, but now in Swift 4, this will result in a compilation error.

将您的方法签名更改为:

Change your method signature to:

open class func drawText(context: CGContext, text: String, point: CGPoint,
    align: NSTextAlignment, attributes: [NSAttributedString.Key : Any]?)

为 Swift 4.2 更新!NSAttributedStringKey 已重命名为 NSAttributedString.Key.

Updated for Swift 4.2! NSAttributedStringKey has been renamed to NSAttributedString.Key.

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

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