Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 2: Cannot convert value of type '[NSObject : AnyObject]' to expected argument type '[String : AnyObject]'

Tags:

swift

swift2

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
}
like image 989
Nursultan Bagidolla Avatar asked Dec 05 '25 09:12

Nursultan Bagidolla


1 Answers

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]
like image 138
tktsubota Avatar answered Dec 08 '25 22:12

tktsubota



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!