Swift - 註釋



註釋是程式中不會被編譯器編譯的特殊文字。註釋的主要目的是向我們解釋程式碼的特定行或整個程式中發生了什麼。程式設計師通常會添加註釋來解釋程式中程式碼行的作用。

或者我們可以說註釋是非可執行文字,它們就像給使用者或程式設計師的筆記或提醒。在 Swift 中,我們可以透過三種不同的方式定義註釋:

  • 單行註釋

  • 多行註釋

  • 巢狀多行註釋

Swift 中的單行註釋

單行註釋用於在程式碼中新增只有一行的文字。單行註釋以雙斜槓 (//) 開頭。編譯器或直譯器總是忽略它們,並且不會影響程式的執行。

語法

以下是單行註釋的語法:

// Add your comment here

示例

新增單行註釋的 Swift 程式。這裡我們在程式中新增單行註釋來解釋 for-in 迴圈的工作原理。

import Foundation
let num = 7
let endNum = 10

// For loop to display a sequence of numbers
for x in num...endNum{
   print(x)
}

輸出

7
8
9
10

Swift 中的多行註釋

多行註釋用於在程式中顯示多行非可執行文字,以解釋特定程式碼行的作用,或由開發人員新增警告、註釋等。與其他程式語言一樣,在 Swift 中,多行註釋以斜槓後跟星號 (/*) 開頭,以星號後跟斜槓 (*/) 結尾。

語法

以下是多行註釋的語法:

/* Add your 
Mult-line comment here */

示例

新增多行註釋的 Swift 程式。這裡我們在程式中新增多行註釋來解釋如何新增兩個長度相同的陣列。

import Foundation

let arr1 = [1, 4, 6, 2]
let arr2 = [3, 5, 2, 4]

var result = [Int]()

/* Check the length of the array.
If they are equal then we add them using the + operator 
and store the sum in the result array */
if arr1.count == arr2.count {
   for i in 0..<arr1.count {
      let sum = arr1[i] + arr2[i]
      result.append(sum)
   }
   print(result)
} else {
   print("Arrays must of same length.")
}

輸出

[4, 9, 8, 6]

Swift 中的巢狀多行註釋

從 Swift 4 開始,多行註釋中也包含一個新特性,即巢狀多行註釋。現在允許您巢狀或在另一個多行註釋中新增多行註釋。即使程式碼塊包含多行註釋,它也可以輕鬆註釋掉許多程式碼塊。

語法

以下是巢狀多行註釋的語法:

/* Add your multi-line comment.
/* Add your nested multi-line comment. */
End multi-line comment */

示例

新增巢狀多行註釋的 Swift 程式。這裡我們在程式中新增巢狀多行註釋來新增新增兩個陣列的替代程式碼。

import Foundation
let arr1 = [1, 4, 6, 2]
let arr2 = [3, 5, 2, 4]

var result = [Int]()
/* Checks the length of the array.
If they are equal then we add them using the + operator 
and store the sum in the result array 
/*You can also use the following code to add two arrays:
if arr1.count == arr2.count {
   let result = zip(arr1, arr2).map(+)
   print(result)
*/
*/
if arr1.count == arr2.count {
   for i in 0..<arr1.count {
      let sum = arr1[i] + arr2[i]
      result.append(sum)
   }
   print(result)
} else {
   print("Arrays must of same length.")
}

輸出

[4, 9, 8, 6]
廣告