为什么Swift不提供类成员初始化器? [英] Why doesn't Swift provide classes memberwise initializers?

查看:97
本文介绍了为什么Swift不提供类成员初始化器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么成员初始化程序仅为结构提供?



我是否需要自己编写初始化程序?

解决方案


我是否需要自己编写初始化程序?


是。



A 将成员初始化程序扩展到类并使它们更灵活的建议已经详尽讨论过上的evolution / of-Mon-20151221 / 003902.htmlrel =noreferrer>。



最终,提案已被拒绝由于各种原因,有可能在以后重新访问该主题(在Swift 3之后是r在拒绝中,Chris Lattner指出至少有一个原因,即成员初始化是专门为结构提供的:因为它可以编写纯粹的袋子属性 ,例如 Vec4 CGRect ,开销最小:


2)成员初始糖有利于POD类型和其他财产袋类型(例如Vec4)和Cocoa的许多C结构类型(CGRect等)。在这些情况下,客户端通常希望显式初始化所有字段,并且成员初始化建议消除了这个样板。这种情况就是我们现有的特性尝试服务。


大多数类可能更复杂,你需要更多的控制成员初始化程序,这可能会使功能也要复杂得多。


Why are memberwise initialisers provided for structures only?

Do I need to write the initialisers by myself?

解决方案

Do I need to write the initialisers by myself?

Yes.

A proposal to extend memberwise initializers to classes and make them more flexible has been discussed exhaustively on the Swift Evolution mailing list in Dec 2015/Jan 2016.

Eventually, the proposal has been rejected for various reasons, with the possibility of revisiting the topic later (after Swift 3 is released).

In the rejection, Chris Lattner noted at least one reason why memberwise initialization was offered specifically for structs: because it makes it possible to write pure "bags of properties", such as Vec4 or CGRect, with minimal overhead:

2) Memberwise init sugar strongly benefits "POD" types and other "bags of property" types (e.g. "Vec4"), and many of the C struct types that Cocoa has (CGRect etc). In these cases, clients often want to initialize all of the fields explicitly and a memberwise init proposal eliminates this boilerplate. This case is what our existing feature attempts to service.

Most classes are probably more complex, and you would want more control over the memberwise initializer, which would have made the feature much more complex, too.

这篇关于为什么Swift不提供类成员初始化器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆