ios - Swift 3 奇怪的崩溃(类型推断)

标签 ios swift swift3

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

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?]

现在,如果我不明确地让编译器知道 views[String: Any] 类型(就像注释掉的东西),这段代码就会崩溃,我得到一个整洁的小崩溃,给我一个中指和这条消息:

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

从 Swift 2.x 迁移后,类似的事情随处可见。有人可以阐明这个问题吗?为什么会这样?如何避免这样的事情?如何发现此类崩溃的根源(有些崩溃很难追踪)?

最佳答案

这是 Swift 3 的问题。

显式声明字典:

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

如果您以这种方式创建let views = ["table": self.tableView],您会收到类型为[String:UIView?] 而可选值是主要问题。

Usage AnyAnyObject 的组合。

Swift provides two special types for working with nonspecific types:

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

AnyObject can represent an instance of any class type.

关于ios - Swift 3 奇怪的崩溃(类型推断),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39827040/

相关文章:

ios - 如何在字符串中查找字符串以在 Swift 3 中过滤数据

ios - iCarousel – 使所有项目都可选择,而不仅仅是居中的一个

iOS:使用核心蓝牙库从不同的 View Controller 进行通信

ios - 如何为所有iDevice设置背景图片?

ios - Swift do catch 内部函数不起作用

快速迁移 : Argument labels '(_:)' do not match any available overloads

ios - 如果文件存在,将图像添加到 collectionView Cell

ios - 不兼容的指针类型将 User* 发送到 UserProfile* 类型的参数

ios - 在 Swift 中访问 NSManagedObject 属性

ios - ResponseSerializer 'cannot call value of non-function type ' NSHTTPURLResponse ?'' 与 Swift 3