iosswift4.2nsattributedstringkey

Cannot convert value of type 'NSAttributedString.Key' to expected dictionary key type 'String' error(swift4.2)


Error in below two lines of code while upgrading from swift 3 to swift 4.2

let lineattribute : [String: Any] = [
    NSForegroundColorAttributeName : UIColor(hexString: "#0f88b7ff")!,
    NSUnderlineStyleAttributeName : NSUnderlineStyle.styleSingle.rawValue
]

let attributeString = NSMutableAttributedString(string: "View travelling details", attributes: lineattribute)

error


Solution

  • In Swift 4.2 you have to use NSAttributedString.Key instead of String

    let lineattribute : [NSAttributedString.Key : Any] = [
        .foregroundColor : UIColor(hexString: "#0f88b7ff"),
        .underlineStyle : NSUnderlineStyle.styleSingle.rawValue
    ]
    
    let attributeString = NSMutableAttributedString(string: "View traveling details", attributes: lineattribute)