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

无法转换类型“[String : AnyObject]?

问题描述:

如何将 '[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.