![](/img/trans.png)
[英]Int is not convertible to DictionaryIndex<String, String>
[英]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.