gpt4 book ai didi

ios - "self"在 Swift 中有什么用?

转载 作者:IT王子 更新时间:2023-10-29 05:02:02 30 4
gpt4 key购买 nike

我是 Swift 的新手,我想知道 self 的用途和原因。

我在类和结构中看到过它,但我真的没有发现它们是必要的,甚至没有必要在我的代码中提及它们。它们的用途是什么?为什么?什么情况下需要用到?

我已经阅读了很多关于这个问题的问题和答案,但没有一个能完全回答我的问题,他们总是倾向于将它与我不熟悉的 Java 中的 this 进行比较无论如何。

最佳答案

是的,它与 Java 中的 this 和 Objective-C 中的 self 相同,但是对于 Swift,仅当您需要时才需要 self从闭包中调用属性或方法,或在代码中区分属性名称,例如初始化程序。因此,您可以安全地使用几乎所有的类组件,而无需使用 self,除非您是从闭包中进行调用。

“The self Property Every instance of a type has an implicit property called self, which is exactly equivalent to the instance itself. You use the self property to refer to the current instance within its own instance methods.

The increment() method in the example above could have been written like this:

func increment() {
self.count += 1
}

In practice, you don’t need to write self in your code very often. If you don’t explicitly write self, Swift assumes that you are referring to a property or method of the current instance whenever you use a known property or method name within a method. This assumption is demonstrated by the use of count (rather than self.count) inside the three instance methods for Counter.

The main exception to this rule occurs when a parameter name for an instance method has the same name as a property of that instance. In this situation, the parameter name takes precedence, and it becomes necessary to refer to the property in a more qualified way. You use the self property to distinguish between the parameter name and the property name.

Here, self disambiguates between a method parameter called x and an instance property that is also called x:”

摘自:Apple Inc.“The Swift Programming Language (Swift 2 Prerelease)”。


这就是Ray Wenderlich建议在 Swift 中使用 self 作为他们的教程:

self 使用

为简洁起见,请避免使用 self,因为 Swift 不要求它访问对象的属性或调用其方法。

当需要区分初始化器中的属性名称和参数时,以及当编译器要求在闭包表达式中引用属性时,使用 self:

class BoardLocation {
let row: Int, column: Int

init(row: Int, column: Int) {
self.row = row
self.column = column

let closure = {
println(self.row)
}
}
}

这是 GitHubself 的应用程序的建议:

Only explicitly refer to self when required

当访问 self 的属性或方法时,默认保留对 self 的引用:

private class History {
var events: [Event]

func rewrite() {
events = []
}
}

仅在语言需要时包含显式关键字——例如,在闭包中或参数名称冲突时:

extension History {
init(events: [Event]) {
self.events = events
}

var whenVictorious: () -> () {
return {
self.rewrite()
}
}
}

基本原理:这使得 self 的捕获语义在闭包中更加突出,并避免了其他地方的冗长。

关于ios - "self"在 Swift 中有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26835013/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com