Swift 中的“self”是什么?
我在一个旧项目中找到了这段代码:
guard let `self` = self else {
return .empty()
}
static let `default`: LayoutParameters = { ..some code.. }
我假设 `` 在该语言的旧版本中使用。但我想知道为什么使用/曾经使用它。另外,我想知道如果在最新版本的 Swift 和 Xcode 中不更改代码并“保持原样”是否会出现任何问题。它工作正常吗?我应该将其替换为
guard let self = self else ......
I found this code in one of the old projects:
guard let `self` = self else {
return .empty()
}
static let `default`: LayoutParameters = { ..some code.. }
I assume `` was used in older versions of the language. But I would like to know why it is used/was used. Also, I would like to know if there are any problems if do not change the code and "leave it as is" in the latest versions of Swift and Xcode. Does it work correctly? Should I replace this with
guard let self = self else ......
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
self
是一个关键字,通常您不能在其上下文之外的地方使用关键字和保留字。然而,这有时会产生问题。因此,有一种特殊的语法可以使关键字成为普通标识符,例如:(另请参阅 Swift 变量名称带有`(反引号))
历史上不允许将
self
作为guard-let-else
中的常量名称,因此反引号通常是( ab)使用。从 Swift 4.2 开始就不再需要它们了。
该代码仍然可以正常工作,因为您可以将任何标识符包装在反引号中,并且它只是一个普通的标识符。
self
is a keyword and normally you cannot use keywords and reserved words in places outside their context. However, that sometimes creates problems. For that reason there is a special syntax to make the keyword to be a normal identifier, e.g.:(also see Swift variable name with ` (backtick))
Historically
self
was not allowed as as a constant name insideguard-let-else
and therefore backticks were commonly (ab)used.They are no longer needed since Swift 4.2.
The code will still work correctly since you can wrap any identifier in backticks and it will just be a normal identifier.
Xcode IDE 建议您使用 `` 来帮助在 Foundation SDK 中使用相同的默认密钥。
示例:default是Foundation中的一个常量名称,如果你想使用default来创建新的变量名称是default,你需要添加``。
但是您使用 SwiftLint 和默认规则,使用默认内容名称会产生代码味道。
The Xcode IDE suggestion you using `` to help to use the same default key in Foundation SDK.
Example: default is a constant name in Foundation, if you want using default to create new variable name is default you need add ``.
But you using
SwiftLint
with default rules, Using a default contants name is a code smell.