Swift程序:检查给定字符串是否为关键字


关键字是用于执行某些内部进程或表示预定义操作的保留字。不允许将这些关键字用作变量名、常量名或标识符。Swift支持大约101个关键字。例如,'var'是关键字,但'hey'不是关键字。在这里,我们将学习如何编写一个Swift程序来检查给定的字符串是否为关键字。

算法

  • 步骤1 − 创建一个字符串类型的数组来存储Swift支持的所有关键字。

  • 步骤2 − 创建一个函数,使用contains()函数检查给定的字符串是否为关键字。

  • 步骤3 − 创建一个字符串。

  • 步骤4 − 使用if-else语句,如果给定的字符串是关键字,则打印“Yes”,否则打印“No”。

示例

以下是Swift程序,用于检查给定的字符串是否为关键字。

Open Compiler
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") }

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

YES! var is a keyword
NO! Sky is not a keyword

在上面的代码中,我们创建一个数组,其中存储Swift支持的所有关键字。现在我们创建一个函数,使用contains()函数检查给定的字符串是否在数组中。如果给定的字符串存在于数组中,则该字符串是关键字,因此此函数将返回true。或者,如果给定的字符串不存在于数组中,则该字符串不是关键字,因此此函数将返回false。

结论

这就是我们如何检查给定的字符串是否为关键字的方法。虽然我们不允许使用关键字作为标识符,但如果您希望使用关键字作为标识符,则必须在关键字名称前后使用反引号(`)。例如,`var`。

更新于:2023年2月8日

浏览量:258

开启你的职业生涯

完成课程获得认证

开始学习
广告