After I upgrade my Xcode to the latest version. It shows this error. Not sure what it means.
The ambiguous error occurs when the type of the object is AnyObject and the compiler has no idea whether the object can be key subscripted.
The solution is to cast result down to something suitable.
It seems to be a dictionary
if let dict = result as? [String:AnyObject] {
let userId = dict["id"] as! String
...
}
You have to define the result type, for example if this is a Dictionary try:
let dic: NSDictionary = result
let userId: String = dic["id"] as! String
Related
I've inherited some Swift code that I'm trying to compile.
The following two lines generate an "Ambiguous use of object(forKey:)" error.
let selectorString: String = (req as AnyObject).object(forKey: "selectorString") as! String
let args = (req as AnyObject).object(forKey: "arguments") as! NSArray
The error highlights req as AnyObject as the culprit.
I've found similar issues on S.O., but none seemed to address this particular issue. I may have missed something in the search results.
I'm hoping this is a simple fix, so any help is appreciated.
Everything depends on what req is. If it is something that can be cast as AnyObject and that responds to object(forKey:), your code compiles and runs. For example:
let req : [String:Any] = ["selectorString":"hey", "arguments":["ho"]]
let selectorString: String = (req as AnyObject).object(forKey: "selectorString") as! String
let args = (req as AnyObject).object(forKey: "arguments") as! NSArray
However, if req cannot be cast to AnyObject, you'll get a compile error.
I have the following firebase database
This is how I add data into the database
And this is how I try to get the data out of Database but I get this error EXC_BAD_INSTRUCTION
Your force unwrap is saying that the dictionary should only consist of String: String. But as you can see, the value for the key value is an integer, which will be parsed as an NSNumber according to the Firebase documentation so String: AnyObject is what you want to unwrap as.
let snapshotValue = snapshot.value as Dictionary<String, AnyObject>
A little bit of safer code would be:
guard let snapshotValue = snapshot.value as? Dictionary<String, AnyObject>
else {
return
}
The error appears because my database value is Integer and I want to read it as String.
I am working on an app that uses both FirebaseDatabase and (attempting to use) Firebase Remote Config. I managed to get RemoteConfig to work perfectly, but I am getting the following warning (mind, in a completely different class): Cast from 'FIRRemoteConfigValue!' to unrelated type 'String' always fails
This warning is correct because whenever I try to retrieve data from my firebase database as such (for example):
let id = snapshot.value!["senderId"] as! String
let text = snapshot.value!["text"] as! String
let locationId = snapshot.value!["location"] as! String
...my code breaks with no indication of what happened in the console.
What really confuses me is that the Realtime Database and Remote Config work independently of each other, however when both are enabled, the Realtime Database crashes...is this an unfortunate bug in Firebase? Or is it something that I did wrong when writing my code?
Anything helps, thanks.
The value property in FIRSnapShot is id(AnyObject) requires you to cast to the type by yourself.
Could you try this workaround:
let val = snapshot.value as! NSDictionary?
let id = val!["senderId"] as! String
Just use valueForKey Instead of [] bracket access value.
Buggy COde
let id = snapshot.value!["senderId"] as! String
let text = snapshot.value!["text"] as! String
let locationId = snapshot.value!["location"] as! String
Solution
let id = snapshot.value.valueForKey("senderId") as! String
let text = snapshot.value.valueForKey("text") as! String
let locationId = snapshot.value.valueForKey("location") as! String
FIRRemoteConfigValue don't have support to access value using []
I read a snippet from this POST but have not quite understood.
https://www.hackingwithswift.com/example-code/system/how-to-parse-json-using-nsjsonserialization
I am confused on some syntax in the following snippets.
In the following, I am not knowing why try goes here, it is strange syntax to me. Any information about try and as! for this expression?
let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! [String: AnyObject]
In the following, I am not knowing what is as? [String] doing?
if let names = json["names"] as? [String] {
I know this question might be fundamental, I just need a keyword for me to search the related anwser, thanks. Here is my whole code block.
// define a string
let str = "{\"names\": [\"Bob\", \"Tim\", \"Tina\"]}"
// convert the string into NSUTF8StringEncoding
let data = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
// put the following statements in try catch block
do {
// not knowing why try goes here, strange syntax to me.
// any higher conception about try and as! for this expression
let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! [String: AnyObject]
// json should be an object(dictionary, hash) use the key "names" to store string array into names
// not knowing what is `as? [String]` doing? any keyword for this syntax?
if let names = json["names"] as? [String] {
print(names)
}
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
// not knowing why try goes here, strange syntax to me. what if it fails? as! is what syntax, any keyword to search for it?
The try here is to basically to try to perform the function on that line. If it fails it will go to the catch. Which in this case will just print("Failed to load: \(error.localizedDescription)")
// json should be an object(dictionary, hash) use the key "names" to store string array into names // not knowing what is as? [String] doing? any keyword for this syntax?
The line that you are confuse about is performing a if else on the json object. It check for a key that is name and also want to ensure that its value is a String therefore the as?. In this case if the key name does not exist it will not met the condition. If the value of name is not a String it will not met the condition.
Like what #Martin R mention in the comments, you should read up more on Type Casting in Swift. This should help you. Explanation with some example if you have trouble with Apple Documentation.
As for try catch it is actually use in other languages as well not just Swift. You can read up more here.
I am working with SwiftyJSON which is great. I am however having an issue with storing the JSON(data:) result in a property in my viewController. The standard use of SwiftyJSON works fine.
let json = JSON(data: data)
let name = json[1]["name"].string
My problem occurs when I try to create a property to store the result of JSON(data:)
// Property
var jsonData : JSON?
someMethod()
{
let json = JSON(data: data)
self.jsonData = json
if let name = self.jsonData[1]["name"].string
{
print(name)
}
}
When I do this I get an error on the following line.
if let name = self.jsonData[1]["name"].string
Cannot find member 'string'
Does anyone know why this is?
You are using an optional property.
var jsonData : JSON?
just use
if let name = self.jsonData?[1]["name"].string
in place of
if let name = self.jsonData[1]["name"].string
in your case complier trying to find a property which can be a nil.