Swift 3 weird crash (output type)

I could not find a more suitable name 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)) } } 

EDIT . If you do not specify an explicit type annotation, the compiler will select [String: UITableView?] In this particular case.

Now, if I cannot explicitly tell the compiler that the views are of type [String: Any] (for example, a commented thing), this code crashes and I get a neat little crash giving me the middle finger with this message

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

Things like this happen everywhere after migrating from Swift 2.x. Can someone shed light on this topic? Why is this happening? How to avoid such things? How to detect the origin of such failures (some of them are very difficult to track)?

+7
ios swift swift3
source share
1 answer

This is a problem with Swift 3.

Declare the dictionary explicitly:

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

In your case, when you create let views = ["table": self.tableView] , you get the type [String:UIView?] , And the main value is an optional value.

Using Any and AnyObject .

Swift provides two special types for working with non-specific types:

Anyone can represent an instance of any type in general, including the function types.

AnyObject can represent an instance of any type of class.

+1
source share

All Articles