简体   繁体   中英

Why can't Swift's runtime put stored properties into the existing structure for extensions?

Swift extensions cannot contain stored properties:

Because properties need storage, adding properties would change the memory structure of the class

If we look closely at the runtime class struct, the Ivar list holds the property storage, and the method list also holds details about the methods that invoke the class objects. And extensions add features in the form of methods to the classes. The extraSpace in a class struct holds the extension struct. Since we can add methods to extensions this way even after the objects have been created -- and to hold the extension methods, memory has to be allocated -- why can't we add ivars?

Because extensions apply to the entire type (struct/class). ivar storage must be allocated for each instance, and instances may already have been created by the time the extension is added to the system. The metatype information can be updated; all the existing instances (which may be stored inside of other instantiated types) cannot be. There is no list of "all existing instances" that you could go and reallocate (as well as reallocating their containers).

Remember that extensions can be applied by other modules, so they may be dynamically attached whenever the module is loaded (which is not even promised to be at launch time at all, let alone before code starts running).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM