gpt4 book ai didi

swift - 将成员标记为私有(private)导致 Argument Passed to Call That Takes No Arguments

转载 作者:行者123 更新时间:2023-12-04 07:44:09 26 4
gpt4 key购买 nike

编译:

struct Foo {
var g: Double = 5.0
}

struct Bar {
var h: Double = 5.0
var foo = Foo()
}

var bar = Bar(h: 6)

添加“private”并且不再编译,标题中有上述错误:
struct Foo {
var g: Double = 5.0
}

struct Bar {
var h: Double = 5.0
private var foo = Foo()
}

var bar = Bar(h: 6) // compiler error on this line

为什么会这样?

最佳答案

这是因为对于一个结构,如果它的任何成员是私有(private)的,则合成的成员 init 将是私有(private)的。因此,您将获得一个不带参数的 init,因为所有属性都有默认值(如果至少一个非可选属性缺少默认值,则根本不会合成任何 init)。
来自 Swift 编程语言书

The default memberwise initializer for a structure type is considered private if any of the structure’s stored properties are private. Likewise, if any of the structure’s stored properties are file private, the initializer is file private. Otherwise, the initializer has an access level of internal.


因此,在您的情况下,您将需要为您的结构编写自定义初始化

关于swift - 将成员标记为私有(private)导致 Argument Passed to Call That Takes No Arguments,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67285049/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com