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

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

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

    stackoverflow

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

    第 1 条附言  ·  56 天前
    3 条回复    2020-07-30 08:08:32 +08:00
    ufo22940268
        2
    ufo22940268   57 天前
    @Procumbens 好像是两个事情,你看我的 snippet 里面定义的变量名是没有_开头的,但是赋值的时候就加上了_
    Nitroethane
        3
    Nitroethane   57 天前   ❤️ 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
    关于   ·   FAQ   ·   API   ·   我们的愿景   ·   广告投放   ·   感谢   ·   实用小工具   ·   2320 人在线   最高记录 5168   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 18ms · UTC 13:00 · PVG 21:00 · LAX 06:00 · JFK 09:00
    ♥ Do have faith in what you're doing.