6

After migrating the project to swift 5, I'm getting a lot of errors such as

Expression implicitly coerced from 'UIButton?' to 'Any'

I'm not sure what's causing this. One example where this is happening(there are a bunch) is when I'm setting the view.accessibilityElements. The array is supposed to contain : [Any]?... Any idea what's causing this?

Here is an example:

@IBOutlet weak var shareButton: UIButton!
@IBOutlet weak var shareTitleLabel: UILabel!

view.accessibilityElements = [shareButton, shareTitleLabel]

Here is another example:

@IBOutlet weak var titleLabel: UILabel!

let titleConstraints = [
        NSLayoutConstraint(item: titleLabel, attribute: .leading, relatedBy: .equal, toItem: otherView, attribute: .leading, multiplier: 1, constant: horizontalTextInset),
        NSLayoutConstraint(item: titleLabel, attribute: .trailing, relatedBy: .equal, toItem: otherView, attribute: .trailing, multiplier: 1, constant: -horizontalTextInset)
]

When setting the elements above like this, it causes the mentioned error

4

1 回答 1

10

几点观察:

  1. 实际上,导致问题的不是迁移本身。问题只是你现在正在编译它 Swift 5,它现在警告你关于模棱两可的强制。

    由于您没有共享产生此警告的确切代码,因此请考虑产生该警告的示例:

    class ViewController: UIViewController {
    
        @IBOutlet var button: UIButton!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let foo: Any = button
            print(type(of: foo))
    
            // do something with `foo`
        }
    }
    

    那么,看看这段代码,是foo可选的还是未包装的值?在 Swift 5 中,它通过这个警告引起了我们的注意

    警告:表达式从“UIButton?”隐式强制转换?去任何'

    它将向您展示三种可能的自动修复来消除这种歧义,即:

    • 使用nil-coalescing 运算符,??;
    • 强制打开它,!; 或者
    • 只需将其强制as Any转换为明确表示这foo将是可选的,无需展开。
       

    归根结底,我们希望能够轻松地推理我们的代码,而Any类型只会使这变得模棱两可。编译器不再假设您是否想要button解包,而是要求我们明确表达我们的意图。

  2. 为了比较,考虑以下两种情况,其中没有歧义,因此没有警告。例如,考虑到相同的隐式展开可选,这里它知道应该发生隐式展开:

    let foo: UIButton = button
    

    而在这里它知道这foo将是可选的:

    let foo: UIButton? = button
    
  3. 如果你想知道为什么你的隐式解包UIButton!出口被视为UIButton?根本(而不是作为一个ImplicitlyUnwrappedOptional类型或只是自动强制解包它,即使你正在使用Any类型),在Reimplementation of Implicitly Unwrapped Optionals中有一些与此相关的有趣讨论和SE-0054 废除 ImplicitlyUnwrappedOptional 类型

于 2019-03-30T04:27:30.160 回答