Swift程式獲取集合大小


本教程將討論如何編寫Swift程式來獲取集合的大小。

集合是Swift中一種主要的集合型別。它是一個無序的集合,儲存相同資料型別的唯一值。不允許在同一個集合中儲存不同型別的值。集合可以是可變的或不可變的。

為了獲取集合的大小,Swift提供了一個名為count的內建屬性。它將返回指定集合中存在的元素總數。

下面是演示:

輸入

假設我們的給定輸入為:

MySet = [2, 45, 67, 12, 33, 55]

輸出

期望輸出為:

Size = 6

語法

以下是語法:

setName.count

演算法

以下是演算法:

  • 步驟1 - 宣告並初始化一個帶有值的集合。

  • 步驟2 - 使用count屬性查詢集合的大小:

var setSize = myNum.count
  • 步驟3 - 列印輸出

示例1

以下程式演示瞭如何計算集合的大小。

import Foundation import Glibc // Creating a Set of integer Type var myNum: Set = [23, 56, 78, 9, 12, 45] // Finding the size of the Set // using count property var setSize = myNum.count print("Set: ", myNum) print("Size of the set is: ", setSize)

輸出

Set: [45, 12, 23, 56, 9, 78]
Size of the set is: 6

在上面的程式碼中,我們有一個整數型別的集合[45, 12, 23, 56, 9, 78]。現在我們使用count屬性查詢集合的大小:

var setSize = myNum.count

因此,集合的大小為6。

示例2

以下程式演示瞭如何計算集合的大小。

import Foundation import Glibc // Creating a Set of string Type var myNames: Set = ["Susma", "Punita", "Piku", "Poonam", "Soona"] // Creating an empty Set var mySet = Set<String>() // Finding the size of the Set // using count property var setSize1 = myNames.count var setSize2 = mySet.count print("Set 1: ", myNames) print("Size of the set is: ", setSize1) print("Set 2: ", mySet) print("Size of the set is: ", setSize2)

輸出

Set 1: ["Piku", "Susma", "Punita", "Soona", "Poonam"]
Size of the set is: 5
Set 2: []
Size of the set is: 0

在上面的程式碼中,我們有兩個集合:myNames是字串型別["Piku", "Punita", "Poonam", "Soona", “Susma”],mySet是一個空集合。現在我們使用count屬性查詢給定集合的大小:

var setSize1 = myNames.count
var setSize2 = mySet.count

因此,myNames的大小為5,setSize2的大小為0。

更新於:2022年10月20日

358 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告