Xcode 7.1
我在Swift中创建一个简单的布局约束:
override func viewDidLoad()
{
super.viewDidLoad()
let search: UISearchBar = UISearchBar.init()
let viewDict: = ["search" : search, "top" : topLayoutGuide]
let con1 = NSLayoutConstraint.constraintsWithVisualFormat("H:|[search]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict)
let con2 = NSLayoutConstraint.constraintsWithVisualFormat("V:[top][search]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict)
view.addConstraints(con1)
view.addConstraints(con2)
}
此代码无法编译,您将获得:
“NSDictionary不能转换为[String:AnyObject]”
似乎viewDict
的类型推断为NSDictionary
。
但是,以下推断为Dictionary
:
let viewDict = ["search" : search]
并且代码编译。
我可以通过这样的显式输入来修复:
let viewDict: Dictionary<String, AnyObject> = ["search" : search, "top" : topLayoutGuide]
问题是:为什么添加topLayoutGuide会破坏类型推断?
我原以为Swift语法[:]会产生Dictionary
并且我必须使用
let test: NSDictionary = NSDictionary()
test.setValue("hello", forKey: "key1")
如果我想要NSDictionary