繁体   English   中英

Swift Int不能转换为DictionaryIndex吗?

[英]Swift Int is not convertible to DictionaryIndex?

我正在尝试转换这段ojb-c代码:

MPMovieFinishReason finishReason = [notification.userInfo[MPMoviePlayerPlaybackDidFinishReasonUserInfoKey] integerValue];

迅速,因此我有这个:

var finishReason: MPMovieFinishReason = notification.userInfo[MPMoviePlayerPlaybackDidFinishReasonUserInfoKey.integerValue];

但是,这给了我标题中的错误。 我在这里做错了什么?

您有一些问题,首先是直接翻译:

var finishReason: MPMovieFinishReason = notification.userInfo[MPMoviePlayerPlaybackDidFinishReasonUserInfoKey.integerValue];

]放在错误的位置,因此您尝试在integerValue上调用MPMoviePlayer...而不是在字典查找上。

var finishReason: MPMovieFinishReason = notification.userInfo[MPMoviePlayerPlaybackDidFinishReasonUserInfoKey].integerValue;

由于userInfo是NSDictionary而不是Dictionary,因此仍然失败,因此它被映射到[AnyObject:AnyObject] 。似乎自动变形使您失败,因此它退回到了CFString ,后者无法映射到AnyObject。

如果我们将其分解成更多部分,该过程将变得更加清晰:

// Recover the original dictionary, and cast is by input and output, to it
//  all makes sense.  This will allow String as a parameter and return an NSNumber
//  as a result.
let userInfo = notification.userInfo as [String:NSNumber]

// From the userInfo, let's extract the raw NSNumber using lookup
let reason = userInfo[MPMoviePlayerPlaybackDidFinishReasonUserInfoKey]

// Convert the NSNumber into an MPMovieFinishReason enum.  Note that it's 
// 0215 and I'm on ambien so I don't care about the force unwrapping that
// should be optional unwrapping
let finishReason = MPMovieFinishReason.fromRaw(reason!.integerValue)

如果一次只执行一个步骤,则许多问题可以分解为简单得多的问题。 现代编译器对此并没有太打扰,因为它可以识别何时不再使用变量并进行适当的回收。 还要注意,对于这些临时值,请使用let而不是var,因为它们无论如何都不能重复使用。

尝试类型转换函数Int()

即,

var finishReason = Int(notification.userInfo[MPMoviePlayerPlaybackDidFinishReasonUserInfoKey]) as MPMovieFinishReason;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM