Avijit Nagare
Avijit Nagare

Reputation: 8782

Compare if let in swift?

I used this code

  if let breedVaccRecorddStr = self.petInfoDict.objectForKey("breedvaccinationrecord")  {

        }else{
            ALToastView.toastInView(UIApplication.sharedApplication().keyWindow, withText: "No Data Found")
        }

This is my response

 {
        breed = dabour;
        breedvaccinationrecord = "";
        "city_registration" = 123146515;
        "date_of_birth" = "12-10-2014";
        "emergency_contacts" = 1245749876;
        gender = male;
        "owner_name" = Environmental;
        "pt_id" = 4150;
        "pt_images" = "";
        "pt_name" = demo123;
        ptinfo = "http://www.petcsi.com/wp-content/uploads/2015/12/jacky42.jpg";
        "prop_name" = "Bella Vida Estates";
        "qr_tag" = 5215653454;
        species = test;
        "vaccination_records" = test123;
        vaccinationrecord = "";
        "vet_info" = "";
    },

Constant can't be nil so it execute if block. but i am expecting output "No Data Found". their may be image url in that key how to check this?

Upvotes: 0

Views: 83

Answers (2)

Michael
Michael

Reputation: 9044

Your question is not very clear, but I'm guessing that your problem is breedvaccinationrecord contains an empty string, not nil. The if let construct by itself only tests for nil, which is why it's not working for you. However, you can also use a where clause:

let value = self.petInfoDict.objectForKey("breedvaccinationrecord")
if let breedVaccRecorddStr = value where value != ""  {
    // do your stuff
} else {
    ALToastView.toastInView(UIApplication.sharedApplication().keyWindow, withText: "No Data Found")
}

This will execute the else if breedvaccinationrecord is nil or an empty string.

Upvotes: 1

ridvankucuk
ridvankucuk

Reputation: 2407

You should write another if let statement for nil value you expected. Such as:

if let imageString = self.petInfoDict.objectForKey("ptInfo") as String {
//Do something with the string
}
else {

}

Upvotes: 0

Related Questions