Swift 讀取並列印二維陣列的程式
與其他程式語言一樣,Swift 也支援二維陣列。二維陣列被稱為陣列的陣列,它以表格形式儲存相同型別的資料。或者我們可以說,二維陣列是一個用行和列表示同類資料的陣列。
語法
var twoDArray:[[Int]] = [[2, 3],[3, 4]]
為了從使用者處讀取二維陣列,Swift 提供了一個名為 readLine() 的內建函式。readLine() 函式從輸入中讀取一個字元字串。如果呼叫此函式時已達到檔案結尾 (EOF),則它將返回 nil。
func readLine() Or func readLine(strippingNewline: true)
這裡的 strippingNewline 引數是布林型別。如果 strippingNewline 引數的值設定為 true,則表示換行符和字元組合將從結果中去除。否則,它們將被保留。預設情況下,strippingNewline 引數的值為 true。
要列印二維陣列,我們可以使用巢狀 for-in 迴圈。巢狀 for-in 迴圈遍歷給定二維陣列的行和列中存在的每個元素。
for x in 0..<rows { for y in 0..<cols { print(newArray[x][y], terminator: " ") } print("") }
這裡的外部 for-in 迴圈表示二維陣列的行,內部 for 迴圈表示二維陣列的列。下標 `newArray[x][y]` 用於訪問陣列元素。
演算法
步驟 1 − 從使用者處讀取二維陣列的行數和列數。
步驟 2 − 建立並初始化一個具有預設值的二維陣列。
步驟 3 − 現在從使用者處讀取陣列元素。
步驟 4 − 輸入所有陣列元素後,在輸出螢幕上顯示結果二維陣列。
示例
在下面的 Swift 示例中,我們將首先使用 readLine() 函式從使用者處讀取行數和列數。然後,我們建立一個並初始化一個具有預設值 0 的二維陣列。現在,我們根據它們的位置從使用者處讀取二維陣列的每個元素,例如 (0, 1) 元素為 2,(0, 2) 元素為 4,依此類推,這裡 0 代表第 0 行,1 代表第 1 列。輸入所有陣列元素後,顯示最終的二維陣列。
import Foundation import Glibc // Enter the size of rows and columns print("Enter the size of row") let rows = Int(readLine()!)! print("Enter the size of column") let cols = Int(readLine()!)! // Initialise a 2-D array with default values var newArray = [[Int]](repeating: [Int](repeating: 0, count: cols), count: rows) // Enter array elements for x in 0..<rows { for y in 0..<cols { print("Enter element (\(x),\(y)): ") if let input = readLine(), let ele = Int(input) { newArray[x][y] = ele } else { print("Input is not valid. Please enter an integer value.") } } } // Displaying resultant array print("\nFinal \(rows)x\(cols) matrix is:") for x in 0..<rows { for y in 0..<cols { print(newArray[x][y], terminator: " ") } print("") }
輸入
Enter the size of row 3 Enter the size of column 3 Enter element (0,0): 3 Enter element (0,1): 2 Enter element (0,2): 4 Enter element (1,0): 2 Enter element (1,1): 6 Enter element (1,2): 7 Enter element (2,0): 4 Enter element (2,1): 3 Enter element (2,2): 7
輸出
Final 3x3 matrix is: 3 2 4 2 6 7 4 3 7
結論
這就是我們如何讀取和列印二維陣列的方法。使用上述方法,您可以建立各種型別的矩陣,例如 2x2、3x4、4x3 等。此外,在使用 readLine() 函式時,您必須使用初始化器(例如,對於整數資料型別使用 Int(),對於雙精度資料型別使用 Double())將結果轉換為所需的資料型別,因為 readLine() 函式始終以字串型別返回結果。