gpt4 book ai didi

ios - Swift Int 不能转换为 DictionaryIndex?

转载 作者:行者123 更新时间:2023-11-28 10:26:04 25 4
gpt4 key购买 nike

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

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

快速,因此我有这个:

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

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

最佳答案

你有几个问题,首先是你的直接翻译:

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

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

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

这仍然失败,因为 userInfo 是一个 NSDictionary 而不是一个字典,所以它被映射到 [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,因为它们无论如何都不应该被重用。

关于ios - Swift Int 不能转换为 DictionaryIndex?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25356923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com