Swift 3: Expression implicitly coerced from 'UIView?' to Any

前端 未结 4 983
既然无缘
既然无缘 2020-12-05 03:47

Someone else must have received this message while (or after) converting an iOS project to Swift 3, yet when I do a Google search, I get no relevant results.

Anyway,

4条回答
  •  春和景丽
    2020-12-05 04:30

    This will happen when the function you are calling has a parameter of type Any, and you are passing an optional.

    For example:

    let color: UIColor? = UIColor.red
    UIBarButtonItem.appearance().setTitleTextAttributes([NSFontAttributeName: color], for: .normal)
    

    Notice that color is of type UIColor? and that setTitleTextAttributes expects a dictionary of type [String: Any]?.

    In order to avoid the warning you have to either force unwrap your optional, or cast it to Any.

    UIBarButtonItem.appearance().setTitleTextAttributes([NSFontAttributeName: color!], for: .normal)
    

    or

    UIBarButtonItem.appearance().setTitleTextAttributes([NSFontAttributeName: color as Any], for: .normal)
    

提交回复
热议问题