为什么类型转换在Swift 2.0中不起作用?

时间:2015-11-08 22:06:37

标签: ios swift casting firebase

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

2 个答案:

答案 0 :(得分:4)

你不能下标AnyObject。必须把它投入字典。 您还需要确保这些值是Ints。

  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
                }
        }

答案 1 :(得分:1)

试试这个:

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值以及可能不兼容的类型的最安全的方法。