我有一个我在Swift 1中构建的项目。但是在自动转换为Swift 2之后,它显示了一个错误:无法转换类型的值' [NSObject:AnyObject]'预期参数类型' [String:AnyObject]'。 功能代码:
func createViewContainers() -> NSDictionary {
var containersDict = NSMutableDictionary()
let itemsCount : Int = tabBar.items!.count as Int - 1
for index in 0...itemsCount {
var viewContainer = createViewContainer()
containersDict.setValue(viewContainer, forKey: "container\(index)")
}
var keys = containersDict.allKeys
var formatString = "H:|-(0)-[container0]"
for index in 1...itemsCount {
formatString += "-(0)-[container\(index)(==container0)]"
}
formatString += "-(0)-|"
var constranints = NSLayoutConstraint.constraintsWithVisualFormat(formatString,
options:NSLayoutFormatOptions.DirectionRightToLeft,
metrics: nil,
views: (containersDict as [NSObject : AnyObject]!) as [NSObject : AnyObject]!)
view.addConstraints(constranints)
return containersDict
}
答案 0 :(得分:1)
您无法始终进行简单的自动转换并完成。通常会有一些代码,自动转换器无法解决这些代码,并会将其单独使用或做一些奇怪的事情。在这种情况下,它是将NSMutableDictionary转换为Swift字典。
NSLayoutConstraint.constraintsWithVisualFormat
参数views
采用[String: AnyObject]
字典。这意味着你必须传入一个[String: AnyObject]
字典。
改变这种非常奇怪的转换:
views: (containersDict as [NSObject : AnyObject]!) as [NSObject : AnyObject]!)
到此:
views: containersDict as! [String: AnyObject]