为什么类型转换在 Swift 2.0 中的工作方式不同?

Why does type casting not work the same in Swift 2.0?

firebase!.observeEventType(FEventType.Value, withBlock: { [weak self] (snapshot) in    
    if let stuff: AnyObject = snapshot.value {
            let from_user_id = stuff["from_user_id"] as? Int //warning
            let value = stuff["value"] as? Int  //warning

        }
}

我收到警告:

Cast from 'MDLMaterialProperty?!' to unrelated type 'Int' always fails

observeEventType 声明为:

func observeEventType(eventType: FEventType, withBlock block: ((FDataSnapshot!) -> Void)!) -> UInt
Description 
observeEventType:withBlock: is used to listen for data changes at a particular location. This is the primary way to read data from Firebase. Your block will be triggered for the initial data and again whenever the data changes.
Use removeObserverWithHandle: to stop receiving updates.
Parameters  
eventType   
The type of event to listen for.
block   
The block that should be called with initial data and updates. It is passed the data as an FDataSnapshot.
Returns 
A handle used to unregister this block later using removeObserverWithHandle:
Declared In Firebase.h

snapshot.value 定义为:

var value: AnyObject! { get }
Description 
Returns the contents of this data snapshot as native types.
Data types returned: * NSDictionary * NSArray * NSNumber (also includes booleans) * NSString
Returns 
The data as a native object.
Declared In FDataSnapshot.h

您不能为 AnyObject 添加下标。必须将其转换为字典。 您还需要确保这些值是整数。

  firebase!.observeEventType(FEventType.Value, withBlock: { [weak self] (snapshot) in    
            if let stuff = snapshot.value as? [String:AnyObject] {
                    let from_user_id = stuff["from_user_id"] as? Int
                    let value = stuff["value"] as? Int
                }
        }

试试这个:

firebase!.observeEventType(FEventType.Value, withBlock: { [weak self] (snapshot) in
    if let stuff = snapshot.value as? NSDictionary {
        if let from_user_id = stuff["from_user_id"] as? Int {
            // Do something with from_user_id.
        }
        if let value = stuff["value"] as? Int {
            // Do something with value.
        }
    }
}

在 Swift 2.

中从 AnyObject 进行转换时,使用可选绑定将是处理潜在 nil 值以及潜在不兼容类型的最安全方法