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

前端 未结 4 924
既然无缘
既然无缘 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:27

    Problem

    The expected type is Any but the type provided was UIView?

    The problem is with the optional, just make sure an instance of UIView is passed and things would work.

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-05 04:40

    In my case it was an issue related to a dictionary without explicit type:

    let dict = ["key": value]
    

    Than I solved specifying the type:

    let dict: [String: Any] = ["key": value]
    

    In your case you can specify your value type:

    let dict: [String: UIView] = ["key": value]
    
    0 讨论(0)
  • 2020-12-05 04:44

    Looks like a bug in the Swift compiler:

    https://bugs.swift.org/browse/SR-2921

    Currently, I'm seeing this with Xcode 8.1 and 8.2 beta 1.

    In your case, the warning should identify the source file, but not the line - as you stated. You will have to hunt around for calls to functions with Any parameters.

    Good new is that it appears fixed in an upcoming Swift toolchain.

    I believe this is fixed in Xcode 8.3 beta 1 (but have not confirmed)

    0 讨论(0)
提交回复
热议问题