Rome Torres
Rome Torres

Reputation: 1081

IOS Swift error reading Json String value

I am getting data from a URL and it is coming back in Json . What I am trying to do is color a certain button Blue if a particular Json column does not contain null or Nil . This is My Json

{"votes":"0","vote_status":null},{"votes":"1","vote_status":"11"}

as you can see the field vote_status returns as a String however if the value is null then it doesn't have any quotation marks around it . How can I check for Null values in my code

// This will store all the vote_status values
    var VoteStatus =  [String]()

  // captures the value 
        if var vote_Status = Stream["vote_status"] as? String {

                            self.VoteStatus.append(vote_Status)
                        }

However I get an error fatal error: Index out of range

Which I am positive it is because the NuLL values does not have any strings . Is there a way I can check for NULL values and change them to something like "null" ? I have tried doing it this way

  if var voteStatus = Stream["vote_status"] as? String {
                                if vote_Status == nil {
                                   vote_Status = "null"
                                }
                                self.VoteStatus.append(vote_Status)
                            }

and it states that comparing non-optional value of type String to nil is always false . The code above compiles but gives an error on Runtime . I am new to Swift but any suggestions would be great..

Upvotes: 0

Views: 248

Answers (1)

creeperspeak
creeperspeak

Reputation: 5523

The reason you're getting that compiletime error is that if this passes: if var voteStatus = Stream["vote_status"] as? String { then that is a guarantee that Stream["vote_status"] is a non-nil String value. If you want to do something different if that IS a nil, then just put an else statement:

if var voteStatus = Stream["vote_status"] as? String {
    //Do whatever you want with a guaranteed, non-nil String
} else {
    //It's nil
}

If you also want to treat the string "null" as a nil value, you can add one little bit:

if var voteStatus = Stream["vote_status"] as? String, voteStatus != "null" {
    //Do whatever you want with a guaranteed, non-nil, non-"null" String
} else {
    //It's nil or "null"
}

The index out of range error is likely caused by something that we're not seeing in your code. Is Stream itself an optional? In your second example are you forgetting to initialize your voteStatus array?

Upvotes: 1

Related Questions