Swift 里面的"_"是什么作用

2020-07-30 07:42:11 +08:00
 ufo22940268
struct MyView: View {
    @Binding var a: Bool
    init(a: Binding<Bool> = .constant(true)) {
        _a = a
    }

    var body: some View {
        Text("MyView")
    }
}

stackoverflow

这里面的_a中的_是什么作用,我在文档上没有找到

3107 次点击
所在节点    Swift
3 条回复
Procumbens
2020-07-30 07:45:07 +08:00
ufo22940268
2020-07-30 08:02:58 +08:00
@Procumbens 好像是两个事情,你看我的 snippet 里面定义的变量名是没有_开头的,但是赋值的时候就加上了_
Nitroethane
2020-07-30 08:08:32 +08:00
In Objective-C when you declare a property @synthesize would create the getter and setters for you automatically since clang 3.2. So, the default @synthesize for a property "foo" would look like this:

@synthesize foo = _foo

because of that _foo would then be the iVar. In other words you could have done the @synthesize yourself and called the iVar whatever you liked:

@synthesize foo = myiVarFoo

so in this case there is no "_"

So now in Swift from the documentation:

Swift unifies these concepts into a single property declaration. A Swift property does not have a corresponding instance variable, and the backing store for a property is not accessed directly.
So from the documentation it's clear that swift does not have a corresponding instance variable thus no need to have the "_" around anymore.


https://stackoverflow.com/a/24215607

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/694206

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX