簡體   English   中英

檢查字典中的對象是否為Int(Swift)

[英]Check if an Object in a Dictionary is an Int (Swift)

我對編寫iOS編程還比較陌生,還沒有完全了解可選參數,向下轉換,字典和相關的有趣概念。 在以下方面,我將不勝感激。

我正在從數據庫下載數據,並希望對數據進行檢查以避免崩潰。 在這種特殊情況下,我想在執行任務以避免崩潰之前檢查字典中的對象是否為Int。

//The downloaded dictionary includes Int, Double and String data
var dictionaryDownloaded:[NSDictionary] = [NSDictionary]()

//Other code for downloading the data into the dictionary not shown.

for index in 1...dictionaryDownloaded.count {

    let jsonDictionary:NSDictionary = self.dictionaryDownloaded[index]

    if (jsonDictionary["SUNDAY OPEN TIME"] as? [Int]) != nil {
        self.currentlyConstructingRecommendation.sundayOpenTime = jsonDictionary["SUNDAY OPEN TIME"] as! Int!
    }

    self.recommendationsArray.append(currentlyConstructingRecommendation)
}

我遵循了相關問答中的方法。 但是,問題是“如果(jsonDictionary [“ SUNDAY OPEN TIME”] as?[Int])!= nil”這一行從不成立。 我相信這是因為該值是一個可選對象。 我嘗試將字典調整為[String:AnyObject]類型,但這沒有影響。

我被困住了,您的任何想法都將不勝感激。 請讓我知道是否有更多有用的細節。 謝謝!

使用以下代碼: jsonDictionary["SUNDAY OPEN TIME"] as? [Int] jsonDictionary["SUNDAY OPEN TIME"] as? [Int] ,您正在嘗試將值轉換為Array<Int> ,而不是Int

並且在代碼中,您還有另一個缺陷: index in 1...dictionaryDownloaded.count index到達dictionaryDownloaded.count時,這將導致索引超出范圍異常。

因此,一個快速的解決方法是:

for index in 0..<dictionaryDownloaded.count {

    let jsonDictionary:NSDictionary = self.dictionaryDownloaded[index]

    if (jsonDictionary["SUNDAY OPEN TIME"] as? Int) != nil {
        self.currentlyConstructingRecommendation.sundayOpenTime = jsonDictionary["SUNDAY OPEN TIME"] as! Int!
    }

    self.recommendationsArray.append(currentlyConstructingRecommendation)
}

但我建議您以一種更加快捷的方式進行操作。

for jsonDictionary in dictionaryDownloaded {

    if let sundayOpenTime = jsonDictionary["SUNDAY OPEN TIME"] as? Int {
        self.currentlyConstructingRecommendation.sundayOpenTime = sundayOpenTime
    }

    self.recommendationsArray.append(currentlyConstructingRecommendation)
}

我認為您已經將Int (這是一個整數)與[Int] (這是一個整數s數組 )混淆了。 此外,這段代碼是多余的:

if (jsonDictionary["SUNDAY OPEN TIME"] as? [Int]) != nil {
    self.currentlyConstructingRecommendation.sundayOpenTime = jsonDictionary["SUNDAY OPEN TIME"] as! Int!
}

您用的出色as? 操作符執行條件轉換,但隨后您將結果丟棄,並將危險as! 在下一行。 您可以使用if let更安全,更清晰:

if let sundayOpenTime = jsonDictionary["SUNDAY OPEN TIME] as? Int {
    self.currentlyConstructingRecommendation.sundayOpenTime = sundayOpenTime
}

這將類型強制轉換為Int ,如果結果不是nil ,則將其解包並sundayOpenTime設置sundayOpenTime 然后,在下一行中使用Int類型的這個新的sundayOpenTime常量。 但是,如果強制轉換的結果 nil ,則整個if語句將失敗,我們將繼續進行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM