首页 > 解决方案 > 无法将“NSAttributedString.Key”类型的值转换为预期的字典键类型“String”错误(swift4.2)

问题描述

从 swift 3 升级到 swift 4.2 时出现以下两行代码错误

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

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

错误

标签: iosswift4.2nsattributedstringkey

解决方案


Swift 4.2中你必须使用NSAttributedString.Key而不是String

let lineattribute : [NSAttributedString.Key : Any] = [
    .foregroundColor : UIColor(hexString: "#0f88b7ff"),
    .underlineStyle : NSUnderlineStyle.styleSingle.rawValue
]

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

推荐阅读