gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 22:14:31 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com