Reputation: 501
I have a project which I built in Swift 1. But after autoconverting to Swift 2, it shows an error: Cannot convert value of type '[NSObject : AnyObject]' to expected argument type '[String : AnyObject]'. The code of function:
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
}
Upvotes: 3
Views: 2894
Reputation: 9401
You can't always do a simple auto-convert and be done. There is usually some code that the auto-converter can't figure out and will leave it alone or do something weird with it. In this case, it is the casting of an NSMutableDictionary to a Swift dictionary.
NSLayoutConstraint.constraintsWithVisualFormat
's parameter views
takes a dictionary of [String: AnyObject]
. So that means you have to pass in a [String: AnyObject]
dictionary.
Change this very odd conversion:
views: (containersDict as [NSObject : AnyObject]!) as [NSObject : AnyObject]!)
to this:
views: containersDict as! [String: AnyObject]
Upvotes: 1