我试图转换这段ojb-c代码:
MPMovieFinishReason finishReason = [notification.userInfo[MPMoviePlayerPlaybackDidFinishReasonUserInfoKey] integerValue];
快点,因此我有这个:
var finishReason: MPMovieFinishReason = notification.userInfo[MPMoviePlayerPlaybackDidFinishReasonUserInfoKey.integerValue];
然而,这给了我标题中的错误。 我在这里做错了什么?
答案 0 :(得分:4)
您有一些问题,首先是您的直接翻译:
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,因为它们不应该被重用。
答案 1 :(得分:0)
尝试使用类型转换函数Int()
即,
var finishReason = Int(notification.userInfo[MPMoviePlayerPlaybackDidFinishReasonUserInfoKey]) as MPMovieFinishReason;