Xcode 6 Beta7 NSDictionary for Swift

Among the floods of errors that I got from upgrading to beta 7, I got this specific one that makes me dizzy ...

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

Error: Cannot convert expression of type type 'Dictionary' to type 'StringLiteralConvertible' For a method that needs "views", you need an NSDictionary, so I can't just use the Swift Dictionary.

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

+3
source share
1 answer

The problem is that UIScrollView.superview is optional, so you need to put the expanded value in the dictionary

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

Use more secure logic instead of implicitly deployed (i.e. check that superview not equal to zero) if you are not 100% sure that it contains a value other than zero.

Even if the views variable is of type NSDictionary , the dictionary literal you use to initialize is evaluated in the swift dictionary — then it silently connects to the NSDictionary .

The reason the compiler complains is because being _scrollView.superview optional, it could potentially be nil, and this is not allowed.

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

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

+7
source

Source: https://habr.com/ru/post/976188/


All Articles