Swift 4 conversion error: Cannot convert value of type 'String' to expected argument type 'NSAttributedStringKey'

Swift 4 conversion error: Cannot convert value of type 'String' to expected argument type 'NSAttributedStringKey'

当我从 Swift 3 转换为 Swift 4 时,我在 "NSAttributedStringKey" 上遇到了一些错误。

这是我的代码:

func height(_ width: CGFloat, font: UIFont, lineBreakMode: NSLineBreakMode?) -> CGFloat {
    var attrib: [NSAttributedStringKey: Any] = [.font: font]
    if lineBreakMode != nil {
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineBreakMode = lineBreakMode!
        attrib.updateValue(paragraphStyle, forKey: NSAttributedStringKey.paragraphStyle.rawValue)
    }
    let size = CGSize(width: width, height: CGFloat(DBL_MAX))
    return ceil((self as NSString).boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes:attrib, context: nil).height)
}

这是我的错误:

Cannot convert value of type 'String' to expected argument type 'NSAttributedStringKey'

有什么建议吗?我是 iOS 的新人,所以请更准确。

您需要删除对 .paragraphStyle 键使用 .rawValue

另请注意,对于 Swift 4.2(或更高版本),您需要将 NSAttributedStringKey 的任何使用替换为 NSAttributedString.Key

DBL_MAX 已弃用。使用 .greatestFiniteMagnitude 而不是 CGFloat(DBL_MAX).

强制展开可选的 lineBreakMode 参数将导致您的应用在传入 nil 时崩溃。