V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
ufo22940268
V2EX  ›  Swift

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

  •  
  •   ufo22940268 ·
    ufo22940268 · Jul 30, 2020 · 3684 views
    This topic created in 2098 days ago, the information mentioned may be changed or developed.
    struct MyView: View {
        @Binding var a: Bool
        init(a: Binding<Bool> = .constant(true)) {
            _a = a
        }
    
        var body: some View {
            Text("MyView")
        }
    }
    

    stackoverflow

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

    Supplement 1  ·  Jul 31, 2020
    3 replies    2020-07-30 08:08:32 +08:00
    ufo22940268
        2
    ufo22940268  
    OP
       Jul 30, 2020
    @Procumbens 好像是两个事情,你看我的 snippet 里面定义的变量名是没有_开头的,但是赋值的时候就加上了_
    Nitroethane
        3
    Nitroethane  
       Jul 30, 2020   ❤️ 1
    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
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1417 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 23:54 · PVG 07:54 · LAX 16:54 · JFK 19:54
    ♥ Do have faith in what you're doing.