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

标签 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

        }
}

我收到警告:

从“MDLMaterialProperty?!”转换到不相关的类型 'Int' 总是失败

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

关于ios - 为什么类型转换在 Swift 2.0 中的工作方式不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33599560/

相关文章:

java - null 真的很特别吗?

Java readObject 和继承的转换

ios - 这里 map iOS Premium SDK, map 未加载

ios - 如何以编程方式在所有 iOS 设备上的 View 之间保持相等的空间?

ios - Objective-C - KVC 的底层是如何工作的?

ios - 发布请求后发回回复

Swift8 tableview 导出在弹出窗口后变为 nil。 fatal error : unexpectedly found nil while unwrapping an Optional value

ios - CocoaPods 未与项目链接

swift - 从 XIB-file-Button 显示 ViewController - Swift

java - Java(字节)文字转换效率高吗?