Swift 3奇怪的崩溃(类型推断) [英] Swift 3 weird crashes (type inference)

查看:365
本文介绍了Swift 3奇怪的崩溃(类型推断)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到更合适的标题。这是场景:

I couldn't find a more appropriate title for this. This is the scenario:

final class Something : UIViewController {
    fileprivate var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView = UITableView(frame: CGRect.zero, style: .plain)
        self.tableView.translatesAutoresizingMaskIntoConstraints = false
        //Delegate, register cell, ...

        self.view.addSubview(self.tableView)
        let views/*: [String: Any]*/ = ["table": self.tableView]

        //THIS LINE NOW WILL CRASH
        self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|-0-[table]-0-|", options: [], metrics: nil, views: views))
        self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[table]-0-|", options: [], metrics: nil, views: views))
    }
}

编辑:如果你没有放置显式类型注释,编译器会推断 [String:UITableView?] 在这种特殊情况下。

EDIT: If you don't put an explicit type annotation the compiler will infer [String: UITableView?] in this particular case.

现在如果我没有表达请让编译器知道视图类型为 [String:Any] (如注释掉的东西)此代码崩溃,我得到一个整洁的小崩溃给我一个中指以及此消息:

Now if I don't explicitly let the compiler know that views are of type [String: Any] (like the commented out thingie) this code crashes and I get a neat little crash giving me a middle finger along with this message:

-[_SwiftValue nsli_superitem]: unrecognized selector sent to instance 0x60000044a560

从Swift 2.x迁移后,这样的事情发生在各处。有人可以就这个问题说清楚吗?为什么会这样?如何避免这样的事情?如何发现此类崩溃的起源(有些很难追查)?

Things like this are happening all over the place after migrating from Swift 2.x. Can someone please shed some light on the subject? Why is this happening? How to avoid things like this? How do discover origins of such crashes (some are very hard to track down)?

推荐答案

这是Swift 3的一个问题。

This is a issue with Swift 3.

明确声明字典:

let views: [String:UIView] = ["table":self.tableView]

在你创建时的情况下这种方式让views = [table:self.tableView] 你收到的类型是 [String:UIView?] 和可选值是主要问题。

In you're case when you create in this manner let views = ["table": self.tableView] you receive type that is [String:UIView?] and the optional value is the main problem.

用法 任何 AnyObject


Swift提供两种特殊类型来处理非特定类型:

Swift provides two special types for working with nonspecific types:

任何可以代表任何实例输入类型,包括函数
类型。

Any can represent an instance of any type at all, including function types.

AnyObject可以表示任何类类型的实例。

AnyObject can represent an instance of any class type.

这篇关于Swift 3奇怪的崩溃(类型推断)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆