我将应用转换为swift3并遇到以下问题。
@objc required init(response: HTTPURLResponse, representation: [NSObject : AnyObject])
{
if (representation.value(forKeyPath: "title") is String) {
self.title = **representation.value**(forKeyPath: "title") as! String
}
我收到以下错误:
类型[NSObject:AnyObject]的值没有成员值。
在旧版本的代码中,我只使用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 :(得分: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
参考:
请注意明确使用'as'
以使String
返回NSString
。桥接不是隐藏的,因为他们希望您使用值类型(String
)而不是引用类型(NSString
)。所以这有点麻烦。
值类型相对于引用类型的主要优点之一是 他们可以更容易地推断您的代码。更多 有关值类型的信息,请参阅Swift中的类和结构 编程语言(Swift 3)和WWDC 2015会话414 Building 在Swift中使用值类型的更好的应用程序。