Swift 4 Cannot convert value of type '[String : AnyObject]?' to expected argument type '[NSAttributedStringKey : Any]?'

前端 未结 4 2041
悲哀的现实
悲哀的现实 2020-12-19 13:16

I have just updated to Xcode 9 and converted my app from swift 3 to swift 4. I have graphs which use strings to label the axes and other variables. So I have a moneyAxisStri

4条回答
  •  悲&欢浪女
    2020-12-19 13:53

    NSAttributedStringKey was changed to a struct in Swift 4. However, other objects that use NSAttributedStringKey apparently didn't get updated at the same time.

    The easiest fix, without having to change any of your other code, is to append .rawValue to all your occurrences of NSAttributedStringKey setters - turning the key names into Strings:

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

    Note that you won't need the ! at the as now, either.

    Alternatively, you can skip the as cast at the end by declaring the array to be [String : Any] upfront:

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

    Of course, you still need to append the .rawValue for each NSAttributedStringKey item you set.

提交回复
热议问题