BadmintonCat
BadmintonCat

Reputation: 9586

Xcode 6 Beta7 NSDictionary to Swift

Among the deluge of errors I got from updating to Beta 7 I got this particular one that makes me head-scratching ...

        let views:NSDictionary =
        [
            "leftView": _leftVC.view,
            "rightView": _rightVC.view,
            "outerView": _scrollView.superview
        ];

Error: Cannot convert the expression't type 'Dictionary' to type 'StringLiteralConvertible' The method that needs 'views' needs an NSDictionary so I can't just use a Swift Dictionary.

How would I adapt the above code to satisfy Xcode6 Beta7?

Upvotes: 3

Views: 3243

Answers (1)

Antonio
Antonio

Reputation: 72790

The problem is that UIScrollView.superview is an optional, so you have to put the unwrapped value in the dictionary

let views:NSDictionary =
[
    "leftView": _leftVC.view,
    "rightView": _rightVC.view,
    "outerView": _scrollView.superview!
];

Use a safer logic instead of an implicitly unwrapped (i.e. check that superview is not nil), unless you are 100% sure it contains a non nil value.

Even if the views variable is of NSDictionary type, the dictionary literal you are using to initialize it evaluates to a swift dictionary - it is then silently bridged to a NSDictionary.

The reason why the compiler complains is that being _scrollView.superview an optional, it can potentially be nil, and that's not allowed.

As noted by @JackLawrance, a dictionary can have non uniform value types even when initialized with literals.

Sidenote: when will we get more meaningful error messages? :)

Upvotes: 7

Related Questions