Swift 4 Conversion error - NSAttributedStringKey: Any

前端 未结 4 1991
孤城傲影
孤城傲影 2020-12-01 10:23

I converted my app recently and I keep getting the error

\"Cannot convert value of type \'[String : Any]\' to expected argument type \'[NSAttributedS

4条回答
  •  再見小時候
    2020-12-01 10:57

    Why you got this error

    Previously, your attributes is defined as [String: Any], where the key comes from NSAttributedStringKey as a string or NSAttributedString.Key in Swift 4.2

    During the migration, the compiler tries to keep the [String: Any] type. However, NSAttributedStringKey becomes a struct in swift 4. So the compiler tries to change that to string by getting its raw value.

    In this case, setTitleTextAttributes is looking for [NSAttributedStringKey: Any] but you provided [String: Any]

    To fix this error:

    Remove .rawValue and cast your attributes as [NSAttributedStringKey: Any]

    Namely, change this following line

    let attributes = [NSAttributedStringKey.font.rawValue:
        UIFont(name: "Helvetica-Bold", size: 15.0)!, 
        NSAttributedStringKey.foregroundColor: UIColor.white] as! [String : Any]
    

    to

    let attributes = [NSAttributedStringKey.font:
        UIFont(name: "Helvetica-Bold", size: 15.0)!, 
        NSAttributedStringKey.foregroundColor: UIColor.white] as! [NSAttributedStringKey: Any]
    

    And in Swift 4.2,

     let attributes = [NSAttributedString.Key.font:
        UIFont(name: "Helvetica-Bold", size: 15.0)!, 
        NSAttributedString.Key.foregroundColor: UIColor.white] as! [NSAttributedStringKey: Any]
    

提交回复
热议问题