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

ufo22940268 14天前 11

struct MyView: View {
    @Binding var a: Bool
    init(a: Binding<Bool> = .constant(true)) {
        _a = a
    }

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

stackoverflow

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

最新回复 (3)
  • Procumbens 10天前
    引用 2
    https://stackoverflow.com/questions/30609636/what-does-an-underscore-before-a-swift-variable-mean/30609658
  • 楼主 ufo22940268 10天前
    引用 3
    @Procumbens 好像是两个事情,你看我的 snippet 里面定义的变量名是没有_开头的,但是赋值的时候就加上了_
  • Nitroethane 10天前
    引用 4
    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
  • 游客
    5
返回