gpt4 book ai didi

ios - 为什么我需要在 Swift 中为 struct 编写初始化程序才能在单元测试中使用它?

转载 作者:IT王子 更新时间:2023-10-29 05:14:54 25 4
gpt4 key购买 nike

我正在尝试使用公共(public)结构

public struct Person {
public let name: String
}

在单元测试(XCTest)中:

let person = Person(name: "Paul")

测试构建失败并出现错误:

'Person' cannot be constructed because it has no accessible initializers.

为了构建测试,我需要为结构编写初始化程序。感觉不对,因为结构已经有了初始值设定项。有没有人有更好的解决方案?

Xcode 版本 6.1.1 (6A2008a)

最佳答案

问题在于,您通过结构获得的自动合成初始化程序被合成为 internal,这意味着无法从另一个模块访问它。

您的单元测试目前在另一个模块中运行,因此它们看不到初始化程序。正如 Ben-G 在他的回答中指出的那样,从 Swift 2.0 开始,这已通过 @testable 属性得到解决。

这是 Swift 项目中单元测试普遍失败的一部分。单元测试模块应该对应用程序模块有特殊的访问权限,否则你必须添加大量的访问控制包袱。

来自documentation :

Default Memberwise Initializers for Structure Types

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

As with the default initializer above, if you want a public structure type to be initializable with a memberwise initializer when used in another module, you must provide a public memberwise initializer yourself as part of the type’s definition.

关于ios - 为什么我需要在 Swift 中为 struct 编写初始化程序才能在单元测试中使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27635489/

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