6

I've been trying to find the best way to implement a stored property in an extension, and came across this question: Swift extension stored properties alternative. However, I have not found a reason why in the discussion or anywhere else. Is there a reason why stored properties are not allowed in Swift? And if so, what is the reason?

Community
  • 1
  • 1
Andrew Johnson
  • 579
  • 4
  • 23

1 Answers1

6

Extensions are for extending the functionality of an existing class without changing the memory structure. It's more or less syntactic sugar. Imagine you could add stored properties and methods, what would it be? Nothing else but inheritance. So if you like to add new properties and methods just inherit from the class.

Darko
  • 9,655
  • 9
  • 36
  • 48
  • Inheritance is frowned upon in Swift use, no? – Joseph Beuys' Mum Mar 08 '19 at 21:11
  • It’s not at all. It’s just that inheritance is often overused in many languages. The complete Swift standard library doesn‘t need a single inheritance model, it is fully protocol oriented and value based. (only structs, no classes) But sometimes inheritance fits better for the given use case, it depends on many things. – Darko Mar 08 '19 at 21:18
  • @Darko if stored property modifies the memory structure of the class, will computed property not modify the memory structure of the existing class? – Sujit Baranwal Jul 22 '23 at 07:00
  • @SujitBaranwal No. Computed properties are basically functions, stored in the same static global memory space like functions of a class or struct. Use sizeof() to calculate the size of any type and then add multiple functions or computed properties. Then check sizeof() again on that type. It will be exactly the same size. – Darko Jul 23 '23 at 20:20