V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
ufo22940268
V2EX  ›  Swift

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

  •  
  •   ufo22940268 ·
    ufo22940268 · 2020-07-30 07:42:11 +08:00 · 3093 次点击
    这是一个创建于 1585 天前的主题,其中的信息可能已经有所发展或是发生改变。
    struct MyView: View {
        @Binding var a: Bool
        init(a: Binding<Bool> = .constant(true)) {
            _a = a
        }
    
        var body: some View {
            Text("MyView")
        }
    }
    

    stackoverflow

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

    第 1 条附言  ·  2020-07-31 15:55:48 +08:00
    3 条回复    2020-07-30 08:08:32 +08:00
    ufo22940268
        2
    ufo22940268  
    OP
       2020-07-30 08:02:58 +08:00
    @Procumbens 好像是两个事情,你看我的 snippet 里面定义的变量名是没有_开头的,但是赋值的时候就加上了_
    Nitroethane
        3
    Nitroethane  
       2020-07-30 08:08:32 +08:00   ❤️ 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
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2180 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 01:19 · PVG 09:19 · LAX 17:19 · JFK 20:19
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.