Sobes.tech
Junior — Middle

Is it possible to add new properties to an object through type extension?

sobes.tech AI

Answer from AI

In iOS (Swift), extensions allow adding new methods, computed properties, and initializers to existing types, but cannot add new stored properties.

This is because extensions cannot modify the internal structure of an object, only extend its functionality.

If you need to add a new property, you typically use:

  • computed properties in extensions (without storing a value)
  • associated objects (in Objective-C runtime) for storing data

Example of a computed property in an extension:

extension String {
    var reversedString: String {
        return String(self.reversed())
    }
}

let s = "hello"
print(s.reversedString) // "olleh"
Is it possible to add new properties to an object… - sobes.tech