Swift程式:檢查給定字串是否為關鍵字
關鍵字是用於執行某些內部程序或表示預定義操作的保留字。不允許將這些關鍵字用作變數名、常量名或識別符號。Swift支援大約101個關鍵字。例如,'var'是關鍵字,但'hey'不是關鍵字。在這裡,我們將學習如何編寫一個Swift程式來檢查給定的字串是否為關鍵字。
演算法
步驟1 − 建立一個字串型別的陣列來儲存Swift支援的所有關鍵字。
步驟2 − 建立一個函式,使用contains()函式檢查給定的字串是否為關鍵字。
步驟3 − 建立一個字串。
步驟4 − 使用if-else語句,如果給定的字串是關鍵字,則列印“Yes”,否則列印“No”。
示例
以下是Swift程式,用於檢查給定的字串是否為關鍵字。
import Foundation
import Glibc
// Array containing all the keywords
let myKeywords: [String] = ["associatedtype", "init", "protocol", "class", "inout", "public", "deinit", "internal", "rethrows", "enum", "let", "static", "extension", "open", "struct", "fileprivate", "operator", "subscript", "func", "private", "typealias", "var", "import", "precedencegroup", "if", "else", "for", "while", "do", "break", "continue", "return", "in", "case", "repeat", "catch", "fallthrough", "throw", "default", "guard", "switch", "defer", "where", "Any", "nil", "as", "throws", "self", "true", "false", "Self", "try", "is", "super", "associativity", "left", "Protocol", "convenience", "mutating", "required", "didSet", "none", "right", "dynamic", "nonmutating", "set", "final", "optional", "some", "get", "override", "Type", "indirect", "postfix", "unowned", "infix", "precedence", "weak", "lazy", "prefix", "willSet", "#available", "#error", "#imageLiteral", "#colorLiteral", "#fileID", "#keyPath", "#column", "#fileLiteral", "#line", "#dsohandle", "#filePath", "#selector", "#elseif", "#file", "#sourceLocation", "#else", "#function", "#warning", "#endif", "#if"]
// Function to check if the given string is a keyword or not
func checkKeyword(str: String) -> Bool {
return myKeywords.contains(str)
}
// test case 1
let myString1 = "var"
if (checkKeyword(str: myString1) == true) {
print("YES! \(myString1) is a keyword")
}
else {
print("NO! \(myString1) is not a keyword")
}
// test case 2
let myString2 = "Sky"
if (checkKeyword(str: myString2) == true) {
print("YES! \(myString2) is a keyword")
}
else {
print("NO! \(myString2) is not a keyword")
}
輸出
YES! var is a keyword NO! Sky is not a keyword
在上面的程式碼中,我們建立一個數組,其中儲存Swift支援的所有關鍵字。現在我們建立一個函式,使用contains()函式檢查給定的字串是否在陣列中。如果給定的字串存在於陣列中,則該字串是關鍵字,因此此函式將返回true。或者,如果給定的字串不存在於陣列中,則該字串不是關鍵字,因此此函式將返回false。
結論
這就是我們如何檢查給定的字串是否為關鍵字的方法。雖然我們不允許使用關鍵字作為識別符號,但如果您希望使用關鍵字作為識別符號,則必須在關鍵字名稱前後使用反引號(`)。例如,`var`。
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP