gpt4 book ai didi

swift - 我们应该如何初始化结构和类中存储的属性?

转载 作者:行者123 更新时间:2023-11-30 10:01:56 28 4
gpt4 key购买 nike

苹果的documentation状态:

Classes and structures must set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created. Stored properties cannot be left in an indeterminate state.

我还看到了this问题,但仍然找不到答案。

//  struct  

struct FlickrObj { // No Error ????
var title : String
var photographer : String

}

// class

class FlickrObj { // will create error: Class 'FlickrObj' has no initializers
var title : String
var photographer : String

}

Apple 表示类和结构都必须设置其存储的属性,但为什么 Struct 不给出任何编译时错误?‌‌

最佳答案

这是因为,在没有任何显式声明的初始化器的情况下,结构本身声明了隐式成员初始化器 init(title:photographer:)

但是类不会这样做。

因此,该类未能履行初始化约定(所有实例属性必须在实例本身完成初始化之前初始化),但结构并未未能履行约定。

关于swift - 我们应该如何初始化结构和类中存储的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38030546/

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