Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

xcode

ios

swift3

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?

like image 336
RyJ Avatar asked Nov 02 '16 18:11

RyJ


3 Answers

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]
like image 58
2 revs, 2 users 78% Avatar answered Oct 21 '22 08:10

2 revs, 2 users 78%


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)
like image 33
Michael Peterson Avatar answered Oct 21 '22 06:10

Michael Peterson


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)

like image 15
Daniel Avatar answered Oct 21 '22 07:10

Daniel