2017-03-10 30 views
0

我正在從URL獲取數據,它將返回到Json中。我想要做的是如果特定的Json列不包含null或Nil,則將某個按鈕顏色爲藍色。這就是我的JsonIOS Swift錯誤讀取Json字符串值

{ 「票」: 「0」, 「vote_status」:空},{ 「票」: 「1」, 「vote_status」: 「11」}

,你可以看到字段vote_status返回爲一個字符串,但如果該值爲null,那麼它周圍沒有任何引號。我怎麼能在我的代碼檢查空值

// 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) 
         } 

不過,我得到一個錯誤致命錯誤:超出範圍的索引

這我肯定這是因爲空值不具有任何字符串。有沒有一種方法可以檢查NULL值並將它們更改爲「null」之類的內容?我試過這樣做

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

它聲明比較字符串的非可選值與nil總是爲false。上面的代碼編譯但在運行時給出錯誤。我是新來的斯威夫特,但任何建議將是偉大的..

回答

1

你得到該編譯時錯誤的原因是,如果通過:if var voteStatus = Stream["vote_status"] as? String {那麼這是一個保證Stream["vote_status"]是一個非零的字符串值。如果你想要做不同的事情,如果這是一個零,那麼只要把else聲明:

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

如果你也想治療字符串"null"作爲一個零值,你可以添加一個點點:

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" 
} 

index out of range錯誤很可能是由我們在您的代碼中看不到的東西引起的。 Stream本身是可選的嗎?在你的第二個例子中,你忘記初始化你的voteStatus陣列嗎?

+0

非常感謝,這正是我們需要的 –