'coerced to Any' but property is of type UIColor

前端 未结 4 833
深忆病人
深忆病人 2021-01-24 10:42

This

NSAttributedString.Key.foregroundColor: view.tintColor

Triggers this warning

Exp         


        
4条回答
  •  闹比i
    闹比i (楼主)
    2021-01-24 10:46

    setTitleTextAttributes expects a dictionary of [NSAttributedString.Key : Any]

    Everything can be treated as Any and that's why this warning doesn't appear in any other case. The only time it appears is when you do it with Optional. Compiler just wants you to make sure that you know what you're doing with your optional :)

    You asked why it happens in Xcode 10.2 and Swift 5?

    It always worked well for optionals that were declared this way:

    let optionalNumber: Int? = 5 
    

    and never for optionals that were declared this way:

    let implicitlyUnwrappedOptionalNumber: Int! = 5 
    

    look at your example: view.tintColor is

    Why it didn't worked for implicitly unwrapped optionals? Because before Swift 5, ImplicitlyUnwrappedOptional and Optional were two different types! And as I wrote before: It always worked well for optionals (and didn't work for ImplicitlyUnwrappedOptional).

    Right now they are the same type, but implicitly unwrapped optionals have special @_autounwrapped mechanism to differentiate the two.

    Thay started removal of this type in Swift 4.2:

    https://github.com/apple/swift-evolution/blob/master/proposals/0054-abolish-iuo.md

    This proposal seeks to limit the adoption of IUOs to places where they are actually required, and put the Swift language on the path to removing implicitly unwrapped optionals from the system entirely when other technologies render them unnecessary. It also completely abolishes any notion of IUOs below the type-checker level of the compiler, which will substantially simplify the compiler implementation.

    but apparently they completed it in Swift 5:

    https://forums.swift.org/t/possible-misdiagnosis-of-se-0054/9546

    ImplicitlyUnwrappedOptional isn’t going to be a type at all anymore. We put the warnings specifically around the use of ! because that’s easier to detect, but yes, using it in any position that isn’t the top-level type of a variable, parameter, or return value is deprecated and will be removed. (@rudkx has already done a lot of work to actually do that removing in Swift 5, some of which will start showing up even in Swift 4.1.)

提交回复
热议问题