3

What is the reason we can't have the outlets for views in a ViewController's extension?

In the and it's the same class referenced by the same xib.

As described in the swift guide from apple:

Extensions in Swift can:

Add computed instance properties and computed type properties

Define instance methods and type methods

Provide new initializers

Define subscripts

Define and use new nested types

Make an existing type conform to a protocol

I presume as suggested in the comments that it has to do something with memory. While a new stored property will increase the memory for that object a computed one will not.

Durdu
  • 4,649
  • 2
  • 27
  • 47
  • 4
    Extensions can't have stored properties. Extensions are extending an already existing class / struct / enum. When you create an `IBOutlet`, it is created as a stored property. – user1046037 Sep 22 '17 at 07:51
  • 2
    Swift is designed to restrict stored properties in extensions. I think it is to do with the memory allocated for the instance which can't be extended. You could have computed properties / additional functions. – user1046037 Sep 22 '17 at 07:55
  • 1
    You can take `IBAction` to extension but not IBOulet as user1046037 suggests – Prashant Tukadiya Sep 22 '17 at 07:56
  • 1
    An outlet is a (typically weak) reference. That is, a **stored** property that holds the value of the **memory address** of the referenced object (usually `UIView`/`NSView` subclass). That can obviously **not** be achieved with a computed property. – Nicolas Miari Sep 22 '17 at 08:10

1 Answers1

7

According the documentation, extensions cannot add stored properties to the class:

Extensions can add new computed properties, but they cannot add stored properties, or add property observers to existing properties.

Outlets are stored properties that are populated by the storyboards. Therefore you cannot define an outlet in the extension.

You can take a look at following SO question for some reasoning behind not allowing stored properties on extensions.

Milan Nosáľ
  • 19,169
  • 4
  • 55
  • 90