Swift 程式檢查字典是否為空


本教程將討論如何編寫 Swift 程式來檢查字典是否為空。

字典用於以鍵值對的形式儲存資料,這些資料以無序的方式進行整理。這裡的鍵型別相同,值的型別也相同。每個鍵都像字典中關聯值的識別符號一樣,每個值都有一個唯一的鍵。Swift 字典就像真實的字典一樣。它根據識別符號查詢值。

語法

以下是建立字典的語法:

var mydict = [KeyType: ValueType]()
Or
var mydict : [KeyType:ValueType] = [key1:value1, key2:value2, key3:value3]

要檢查給定的字典是否為空,我們可以使用以下任何一種方法:

  • 使用 count 屬性

  • 使用 isEmpty 屬性

方法 1 - 使用 count 屬性

要檢查給定的字典是否為空,我們檢查字典的大小。如果字典的大小為 0,則字典為空,否則不為空。因此,要查詢字典的大小,我們使用 count 屬性。

以下是相同內容的演示:

輸入

假設我們的給定輸入為:

Mydict = [1: “Mona”, 2: “Noh”, 3: “Tarzen”]
NO! The dictionary is not empty
Here Mydict dictionary is not empty because the size of the Mydict is 3

語法

以下是語法:

dictName.count

演算法

以下是演算法:

  • 步驟 1 - 建立具有鍵值對的字典。

  • 步驟 2 - 使用 count 屬性計算字典的大小。

var size1 = mydict1.count
var size2 = mydict2.count
  • 步驟 3 - 如果大小等於 0,則字典為空。否則不為空。

  • 步驟 4 - 列印輸出

示例

以下程式演示瞭如何計算字典的大小。

import Foundation import Glibc // Creating dictionaries var mydict1 : [Int:Int] = [2:34, 4:56, 8:98, 5:3803, 6:23] var mydict2: [Int:String] = [:] // Calculating the size of dictionaries var size1 = mydict1.count var size2 = mydict2.count // Checking if the given dictionaries are empty or not if (size1 == 0){ print("mydict1 is empty") } else{ print("mydict1 is not empty") } if (size2 == 0){ print("mydict2 is empty") } else{ print("mydict2 is not empty") }

輸出

mydict1 is not empty
mydict2 is empty

在這裡,在上面的程式碼中,我們有兩個字典:mydict1 和 mydict2。現在我們使用 count 屬性檢查它們是否為空。所以我們首先使用 count 屬性找到它們的大小。

var size1 = mydict1.count
var size2 = mydict2.count

現在我們檢查它們是否為空:

if (size1 == 0) // Condition is false{
   print("mydict1 is not empty")
}
if (size2 == 0) // Condition is true{
   print("mydict2 is empty")
}

方法 2 - 使用 isEmpty 屬性

要檢查給定的字典是否為空,我們使用 isEmpty 屬性。如果給定的字典為空,則此屬性將返回 true。否則,它將返回 false。

以下是相同內容的演示:

輸入

假設我們的給定輸入為:

Mydict = []
YES! The dictionary is not empty

在這裡,Mydict 字典為空,因此 isEmpty 將返回 true。

語法

以下是語法:

dictName.isEmpty

演算法

以下是演算法:

  • 步驟 1 - 建立具有鍵值對的字典。

  • 步驟 2 - 使用 isEmpty 屬性檢查給定的字典是否為空。

mydict1.isEmpty
  • 步驟 3 - 列印輸出

示例

以下程式演示瞭如何計算字典的大小。

import Foundation import Glibc // Creating dictionaries var mydict1 : [Int:String] = [1: "CAR", 2: "BUS", 3:"BIKE"] var mydict2: [String:String] = [:] // Checking if the given dictionaries are empty or not if (mydict1.isEmpty == true){ print("mydict1 is empty") } else{ print("mydict1 is not empty") } if (mydict2.isEmpty == true){ print("mydict2 is empty") } else{ print("mydict2 is not empty") }

輸出

mydict1 is not empty
mydict2 is empty

在這裡,在上面的程式碼中,我們有兩個字典:mydict1 和 mydict2。現在我們使用 isEmpty 屬性檢查它們是否為空。

if (mydict1.isEmpty == true) // Condition is false{
   print("mydict1 is empty")
}
if (mydict2.isEmpty == true) // Condition is true{
   print("mydict2 is empty")
}
else{
   print("mydict2 is not empty")
}

更新於:2022 年 10 月 20 日

1K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告