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

IosXcodeSwift3

Ios Problem Overview


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, after converting to Swift 3, I have about 30 warnings that say:

> Expression implicitly coerced from 'UIView?' to Any

But the warnings do not point to any specific line of code. They only reference the class where the warning exists.
Does anyone have an insight into this warning or how I might go about silencing them?

Ios Solutions


Solution 1 - Ios

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]

Solution 2 - Ios

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)

Solution 3 - Ios

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)

Solution 4 - Ios

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRyJView Question on Stackoverflow
Solution 1 - IosMadson CardosoView Answer on Stackoverflow
Solution 2 - IosMichael PetersonView Answer on Stackoverflow
Solution 3 - IosDanielView Answer on Stackoverflow
Solution 4 - Iosuser1046037View Answer on Stackoverflow