Swift 3:无法将'NSMutableDictionary'类型的值转换为预期的参数类型'[AnyHashable:Any]!'

时间:2016-09-22 04:25:03

标签: swift swift3

此代码在Swift 3之前有效。(诅咒Swift 3!)

现在它针对<div id="map"></div> <!-- Replace the value of the key parameter with your own API key. --> <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDwqIkJwBb6g4KirOaLnNgE1I6MtWnKxac&callback=initMap&language=ja"> </script>行显示此错误:

  

无法将'NSMutableDictionary'类型的值转换为预期值   参数类型'[AnyHashable:Any]!'

Flurry.logEvent(eventName, withParameters: userData!)投射到userData!会产生此错误:

  

无法将'NSMutableDictionary'类型的值转换为type   '[AnyHashable:Any]'在胁迫中

[AnyHashable : Any]

Swift 3的正确语法是什么?

1 个答案:

答案 0 :(得分:21)

如果Flurry.logEvent(_:withParameters:)占用[AnyHashable: Any],为什么不将其用作本地userData

func logEvent(_ eventName: String, userData: NSMutableDictionary?) {
    // Use <userData> or create new one?
    var userData = userData as NSDictionary? as? [AnyHashable: Any] ?? [:]

    // Set base properties
    userData["Num Tofus"] = gUser.tofus.count
    userData["Num Lifetime Tofus"] = gUser.getLifetimeTofus()

    // Call Flurry
    DispatchQueue.main.async {
        Flurry.logEvent(eventName, withParameters: userData)
    }
}

<强>更新

包含SE-0139SE-0140的Xcode 8.1 GM种子已淘汰,因此下面的列表已更新。

这些是 Objective-C安全类型,设置为[AnyHashable: Any]字典(或设置在[Any]数组中,或者只是传递给Any这是Objective-C中的非null id,其中传递给Objective-C世界:

Swift 3.0.1 / Xcode 8.1

  • 可选值包括nil

nil转换为NSNull,所有非零选项都会被解包。

NSNull可能不是您想要的。仍然要小心检查零。)

  • 所有数字类型和Bool

Int8UInt8Int16UInt16Int32UInt32Int64UInt64 , 以及 IntUIntDoubleFloatCGFloatBool。这些转换为NSNumber

  • String

转换为NSString

  • Array,其中Element是Objective-C safe

转换为NSArray

  • Dictionary,其中KeyValue是Objective-C安全的

转换为NSDictionary

  • Set,其中Element是Objective-C safe

转换为NSSet

  • NSObject后代类型

未转换,按原样使用。

  • 具有对位参考类型的值类型

请参阅列表here

  • NSValue具有
  • 初始值设定项的值类型

NSRangeCGPointCGVectorCGSizeCGRectCGAffineTransformUIEdgeInsetsUIOffsetCATransform3DCMTimeCMTimeRangeCMTimeMappingCLLocationCoordinate2DMKCoordinateSpanSCNVector3SCNVector4SCNMatrix4。 这些类型将转换为NSValueNSRange已在旧版Swifts中转换为NSValue,但没有详细记录。)

坏事(例子)

即使在Swift 3.0.1中,仍有一些值可能会转换为_SwiftValue

  • Swift只有类型(如Swift-only)枚举,struct,tuple ......

(见this list。)

我没有检查所有包装器枚举和结构,但其中一些(例如,Notification.NameNSString)似乎已安全转换。

Swift 3.0.0 / Xcode 8.0

  • 非可选数字类型和Bool

IntUIntDoubleFloatCGFloatBool。这些转换为NSNumber

  • 非可选String

转换为NSString

  • 非可选Array,其中Element是Objective-C safe

转换为NSArray

  • 非可选Dictionary,其中KeyValue是Objective-C safe

转换为NSDictionary

  • 非可选Set,其中Element是Objective-C safe

转换为NSSet

  • 非可选NSObject后代类型

未转换,按原样使用。

  • 具有对位参考类型的非可选值类型

请参阅列表here。 (链接的文章已针对Swift 3.0.1进行了更新。)

坏事(例子)

这些可能会转换为_SwiftValue,这在Objective-C世界中是完全无用的和灾难性的。

  • Int8UInt8Int16UInt16Int32UInt32Int64UInt64
  • 任何可选值,包括nil
  • Swift只有类型(如Swift-only)枚举,struct,tuple ......
相关问题