Search code examples
swiftswift4nsattributedstring

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


When I converted from Swift 3 to Swift 4 I got some error on the "NSAttributedStringKey".

Here's My Code:

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)
}

Here's My Error:

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

Any suggestion? I'm new in iOS so please be more precise.


Solution

  • You need to remove the use of .rawValue for the .paragraphStyle key.

    Also note that for Swift 4.2 (or later) you need to replace any use of NSAttributedStringKey with NSAttributedString.Key.

    DBL_MAX is deprecated. Use .greatestFiniteMagnitude instead of CGFloat(DBL_MAX).

    Force-unwrapping the optional lineBreakMode parameter is going to cause your app to crash if nil is passed in.