Xcode 6 Beta7 NSDictionary 到 Swift [英] Xcode 6 Beta7 NSDictionary to Swift
问题描述
在更新到 Beta 7 后出现的大量错误中,我遇到了一个让我头疼的问题......
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
];
错误:无法将表达式't type 'Dictionary' 转换为 type 'StringLiteralConvertible'需要视图"的方法需要 NSDictionary,所以我不能只使用 Swift 字典.
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.
我将如何修改上述代码以满足 Xcode6 Beta7?
How would I adapt the above code to satisfy Xcode6 Beta7?
推荐答案
问题在于UIScrollView.superview
是一个可选的,所以你必须把解包的值放到字典中
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!
];
使用更安全的逻辑而不是隐式解包(即检查 superview
是否为 nil),除非您 100% 确定它包含非 nil 值.
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.
即使 views
变量是 NSDictionary
类型,您用来初始化它的字典文字也会评估为一个 swift 字典 - 然后它会悄悄地桥接到 <代码>NSDictionary.
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
.
编译器抱怨的原因是 _scrollView.superview
是可选的,它可能为零,这是不允许的.
The reason why the compiler complains is that being _scrollView.superview
an optional, it can potentially be nil, and that's not allowed.
正如@JackLawrance 所指出的,即使使用文字初始化,字典也可以具有非统一的值类型.
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? :)
这篇关于Xcode 6 Beta7 NSDictionary 到 Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!