How to check for null in Dart? - dart

I don't know what I am doing wrong. I thought that to check whether a variable x is not null in Dart, one could simply do x != null. But that does not work in this code below. And, it is not clear to me why. I would appreciate why it is not working.
void getUserAnswers() {
HttpRequest.getString(pathToUserAns).then((String data) {
print("data is: $data");
if (data != null) {
print("data is not null");
}
});
}
The above code gives the following output in the chromium console:
data is: null
data is not null
which does not seem to make sense.

Related

Why I couldn't assign fetched values from Firestore to an array in Swift?

I tried several times with various ways to assign the collected values of documents from firestore into an array. Unfortunately, I could't find a way to solve this issue. I attached the code that I recently tried to implement. It includes before Firestore closure a print statement which print the whole fetched values successfully. However, after the closure and I tried to print the same array and the result is an empty array.
I tried to implement this code
var hotelCities: [String] = []
func getCities() {
db.collection("Hotels").getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
var found = false
let documentDetails = document.data() as NSDictionary
let location = documentDetails["Location"] as! NSDictionary
let city = location["city"]!
if (self.hotelCities.count == 0) {
self.hotelCities.append(String(describing: city))
}
else{
for item in self.hotelCities {
if item == String(describing: city){
found = true
}
}
if (found == false){
self.hotelCities.append(String(describing: city))
}
}
}
}
print(self.hotelCities)
}
print(self.hotelCities)
}
That's actually the expected result, since data is loaded from Firestore asynchronously.
Once you call getDocuments(), the Firestore client goes of and connects to the server to read those documents. Since that may take quite some time, it allows your application to continue running in the meantime. Then when the documents are available, it calls your closure. But that means the documents are only available after the closure has been called.
It's easiest to understand this flow, by placing a few print statements:
print("Before starting to get documents");
db.collection("Hotels").getDocuments() { (querySnapshot, err) in
print("Got documents");
}
print("After starting to get documents");
When you run this code, it will print:
Before starting to get documents
After starting to get documents
Got documents
Now when you first saw this code, that is probably not the output your expected. But it completely explains why the print(self.hotelCities) you have after the closure doesn't print anything: the data hasn't been loaded yet.
The quick solution is to make sure that all code that needs the documents is inside of the close that is called when the documents are loaded. Just like your top print(self.hotelCities) statement already is.
An alternative is to define your own closure as shown in this answer: https://stackoverflow.com/a/38364861

The nil check for presence of an element is not working as expected in functional test case

Suppose I am using a code snippet in setup() method just before running a test case like this:
if EarlGrey().selectElementWithMatcher(grey_accessibilityID("TabBar-Navigation-Search")).assertWithMatcher(grey_sufficientlyVisible()) != nil {
TabBarNavigation().navigateToSearch()
} else {
assentViewModelsSwifts.signInCheck()
assentViewModelsSwifts.enterLoginCredentials("username", password: "password")
let visibleSignInButtonMatcher = grey_allOfMatchers(grey_accessibilityID("Login-Button-SignIn"), grey_sufficientlyVisible())
EarlGrey().selectElementWithMatcher(visibleSignInButtonMatcher).performAction(grey_tap())
TabBarNavigation().navigateToSearch()
Log.info("Landed on Search Page")
}
I am running into an error.
Assertion 'assertWithMatcher: matcherForSufficientlyVisible(>=0.750000)' was not performed because no UI element matching (respondsToSelector(accessibilityIdentifier) && accessibilityID("TabBar-Navigation-Activity")) was found.
Actually I want to check the presence of an element. If element is present, do a certain step or do something else. But although the element is not present on that particular screen, the code inside the loop is not executed.
Any suggestion would be appreciated.
Try below method for nil check:
- (instancetype)assertWithMatcher:(id<GREYMatcher>)matcher error:(__strong NSError **)errorOrNil
Try below code to check nil:
let errorOrNil
EarlGrey().selectElementWithMatcher(grey_accessibilityID("TabBar-Navigation-Search")).assertWithMatcher(grey_sufficientlyVisible(), error:&errorOrNil)
if errorOrNil != nil {
TabBarNavigation().navigateToSearch()
} else {
assentViewModelsSwifts.signInCheck()
assentViewModelsSwifts.enterLoginCredentials("username", password: "password")
let visibleSignInButtonMatcher = grey_allOfMatchers(grey_accessibilityID("Login-Button-SignIn"), grey_sufficientlyVisible())
EarlGrey().selectElementWithMatcher(visibleSignInButtonMatcher).performAction(grey_tap())
TabBarNavigation().navigateToSearch()
Log.info("Landed on Search Page")
}

PFQuery found a nonexistent object - Swift

I'm trying to query a nonexistent object like this code bellow, but always "Mike" is found. What could be wrong? Everything is working great (Save, Delete, Update and Query without error recognition).
var query = PFQuery(className:"Restaurant")
query.whereKey("clientname", equalTo:"Mike")
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if (error == nil) {
print ("Found")
}
else {
print ("Not Found")
}
}
Try checking (debugging) what "objects" actually is. I think you will see that it is an empty array, meaning it did NOT find Mike.
An empty array of results is not a query error. The query succeeds, but finds no objects. So not getting an error does not mean "Found". It just means there was no error.

iOS8/Swift strange null behaviour with response from REST service

Throughout my project I can perfectly check Alamofire responses and data for
if fooData != nil {
//do stuff
}
somehow in this instance Swift seems to have problems checking what the actual incoming type is
what I get if I print it is
<null>
what is this supposed to be? An array of null? Casts to NSDictionary or NSArray both fail.
The Rest response is the same as always throughout the project where I will potentially receive a null value and it gets catched everywhere else.
€dit with more code:
my request:
Alamofire.request(.GET, "\(CurrentConfiguration.serverURL)/api/users/\(CurrentConfiguration.currentUser.id)/friends/\(targetUser)",encoding:.JSON)
.validate()
.responseJSON {(request, response, friendData, error) in
if friendData != nil {
println(friendData!)
//this is where the app obviously crashes as there is nothing inside of "friendData"
let resp = friendData as NSDictionary
//load friendData into the UI
}
}
the print statement gives me the above mentioned null representation, but obviously does not recognize as nil
the response from the node backend comes as
index.sendJsonResponse(res, 200, null);
Try this code in Playground:
let fooData:AnyObject = NSNull()
println(fooData)
It prints <null>.
fooData is not nil, but a instance of NSNull

How to print something so that if it is nil, it will print nil - iOS

I always use NSLog to print out contents of objects when I am debugging my iOS applications. But any time I come across a "nil" object, the program crashes. In Java, if an object is null, it will print "null". Is there a way to do this in Objective-C?
Something like:
if (questionableObject == nil) {
NSLog(#"questionableObject is nil.");
} else {
NSLog(#"questionableObject is: %#", questionableObject);
}
I've only really run into this problem when I send a message to an object inside the NSLog parameter list that uses a nil object as a parameter. Something like this:
if (questionableObject == nil) {
NSLog(#"questionableObject is nil.");
} else {
NSLog(#"result is: %#", [something someMessage:questionableObject]);
}
What do you mean by "print out contents of objects"? If you're dereferencing a nil pointer, that'll cause a problem. If you're just printing the pointer, that should be OK. You can also send messages to nil without problem, so you could do this:
NSLog(#"theObject is: %#", [theObject description]);

Resources