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 
    } 

私は次のエラーを取得:

:私はちょうど表現の型としてANYOBJECT使用していましたが、私はそうするならば、私はそこにエラー AnyObject is not a subtype of NSObjectを取得するコードの古いバージョンで

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

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

注バックNSStringからStringを取得するために必要な'as'を明示的に使用します。参照タイプ(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.

関連する問題