简体   繁体   English

Swift Int不能转换为DictionaryIndex吗?

[英]Swift Int is not convertible to DictionaryIndex?

I'm trying to convert this piece of ojb-c code: 我正在尝试转换这段ojb-c代码:

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

to swift, and as such I have this: 迅速,因此我有这个:

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

However this gives me the error in the title. 但是,这给了我标题中的错误。 What am I doing wrong here? 我在这里做错了什么?

You have a few problems, first of all in your direct translation: 您有一些问题,首先是直接翻译:

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

The ] is in the wrong place, so you're trying to call integerValue on MPMoviePlayer... instead of on the dictionary lookup. ]放在错误的位置,因此您尝试在integerValue上调用MPMoviePlayer...而不是在字典查找上。

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

This is still failing because userInfo is an NSDictionary and not a Dictionary, so it gets mapped to [AnyObject:AnyObject] It seems like the automatic morphing is failing you, so it's falling back to a CFString which isn't mappable to AnyObject. 由于userInfo是NSDictionary而不是Dictionary,因此仍然失败,因此它被映射到[AnyObject:AnyObject] 。似乎自动变形使您失败,因此它退回到了CFString ,后者无法映射到AnyObject。

The process becomes a little clearer if we break it up more: 如果我们将其分解成更多部分,该过程将变得更加清晰:

// 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)

Many problems can be broken down into much simpler problems if you just take it a single step at a time. 如果一次只执行一个步骤,则许多问题可以分解为简单得多的问题。 Modern compilers aren't even too bothered by it as the can recognize when variables are no longer in use and do proper reclamation. 现代编译器对此并没有太打扰,因为它可以识别何时不再使用变量并进行适当的回收。 Also note using let instead of var for those temporary values since they shouldn't be reused anyway. 还要注意,对于这些临时值,请使用let而不是var,因为它们无论如何都不能重复使用。

Try the type-casting function Int() 尝试类型转换函数Int()

ie., 即,

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

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

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