swiftui 里 VIew 中声明的属性会变成参数?那为什么 body 没有变成参数?

2021-08-07 14:43:04 +08:00
 find456789
struct DemoView: View {
    var a = 1
    let b = 2
    var body: some View {
        Image("avatar")
    }
}

比如上面这一段代码,如果在别处引用了 这个 DemoView, 就可以传入参数 a, 但是却不用传入 body,

但是 body 也 是 DemoVIew 内部的 var 呀

有朋友知道为什么吗? 有这方面专门讲解的资料吗(讲解 View 内部的 var 、let 的资料),

我发现很多入门资料都没有针对这个问题讲解(应该是我没有找到讲解这方面的资料)

补充:我有 react 基础

谢谢

634 次点击
所在节点    问与答
4 条回复
ryh
2021-08-07 15:19:34 +08:00
body 不是计算后( computed )的参数吗,a/b 有默认值的也不用传参数啊

@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public protocol View {

/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required ``View/body-swift.property`` property.
associatedtype Body : View

/// The content and behavior of the view.
///
/// When you implement a custom view, you must implement a computed
/// `body` property to provide the content for your view. Return a view
/// that's composed of primitive views that SwiftUI provides, plus other
/// composite views that you've already defined:
///
/// struct MyView: View {
/// var body: some View {
/// Text("Hello, World!")
/// }
/// }
ryh
2021-08-07 15:24:57 +08:00
m1ng
2021-08-07 15:58:09 +08:00
这不是 swiftUI 的问题,是 swift 语言的问题。a 和 b 是存储属性,需要占用 struct 存储空间; body 是计算属性,不占用存储空间,值是通过后面的函数计算出来的。
find456789
2021-08-07 18:30:28 +08:00
@ryh @m1ng
谢谢,是我 swift 基础不扎实, 重新补充了下 struct 的知识,我就明白了, 感谢

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

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

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

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

© 2021 V2EX