[NSObject: AnyObject] 类型的字典没有成员 "value(forKeyPath: ...)"

Dictionary of type [NSObject: AnyObject] has no member "value(forKeyPath: ...)"

我正在将应用程序转换为 swift3 并遇到以下问题。

@objc required init(response: HTTPURLResponse, representation: [NSObject : AnyObject])
{
    if (representation.value(forKeyPath: "title") is String)    {
        self.title = **representation.value**(forKeyPath: "title") as! String
    }

我收到以下错误:

Value of type [NSObject:AnyObject] has no member value.

在旧版本的代码中,我只是使用 AnyObject 作为表示类型,但如果这样做,我会得到错误 AnyObject is not a subtype of NSObject

if (representation.value(forKeyPath: "foo") is String) {
    let elementObj = Element(response: response, representation:**representation.value(forKeyPath: "foo")**!)
}

您正在混合使用 Objective-C 和 Swift 样式。最好实际决定。

桥接回 NSDictionary 不是自动的。

考虑:

let y: [NSObject: AnyObject] = ["foo" as NSString: 3 as AnyObject] // this is awkward, mixing Swift Dictionary with explicit types yet using an Obj-C type inside
let z: NSDictionary = ["foo": 3]
(y as NSDictionary).value(forKeyPath: "foo") // 3
// y["foo"] // error, y's keys are explicitly typed as NSObject; reverse bridging String -> NSObject/NSString is not automatic
y["foo" as NSString] // 3
y["foo" as NSString] is Int // true
z["foo"] // Bridging here is automatic though because NSDictionary is untyped leaving compiler freedom to adapt your values
z["foo"] is Int // true
// y.value // error, not defined

// Easiest of all:
let ynot = ["foo": 3]
ynot["foo"] // Introductory swift, no casting needed
ynot["foo"] is Int // Error, type is known at compile time

参考:

https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/WorkingWithCocoaDataTypes.html

请注意显式使用 'as' 需要将 String 返回到 NSString。桥接并未隐藏,因为他们希望您使用值类型 (String) 而不是引用类型 (NSString)。所以这样故意比较麻烦

One of the primary advantages of value types over reference types is that they make it easier to reason about your code. For more information about value types, see Classes and Structures in The Swift Programming Language (Swift 3), and WWDC 2015 session 414 Building Better Apps with Value Types in Swift.