2016-09-23 14 views
0

我正在將應用程序轉換爲swift3並遇到以下問題。[NSObject:AnyObject]類型的字典沒有成員「value(forKeyPath:...)」

@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")**!) 
} 
+0

'NSObject'和'(forKeyPath:「title」)'不會很好。是否可以使用'[String:AnyObject]'? –

+0

爲什麼不簡單'self.title = representation [「title」]'? – vikingosegundo

+0

你真的知道'value(forKeyPath:'應該做什麼的方法嗎? – vadian

回答

0

你在混合使用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需要。橋接不會隱藏,因爲他們希望您使用參考類型(NSString)上的值類型(String)。所以這是故意更麻煩的。

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.

相關問題