Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: 'var' declaration without getter/setter method not allowed here

Tags:

ios

swift

I've tried to declare IBOutlet property on extension of class. But it give error as

'var' declaration without getter/setter method not allowed here

class ExampleView : UIView
{

}

extension ExampleView
{
    @IBOutlet var btn1, btn2 : UIButton // here I got error.

}

Please any one suggest me correct way to do it?

like image 602
Mani Avatar asked Jun 09 '14 06:06

Mani


2 Answers

From Extensions -> Computed Properties in The Swift Programming Language

NOTE

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


Addition in response to twlkyao's comment: Here is my implementation of the absoluteValue property of a Double

extension Double {
    var absoluteValue: Double {
        if self >= 0 {
            return self
        } else {
            return -self
        }
    }
}

// Simple test -> BOTH println() should get called.
var a = -10.0
if (a < 0) {
    println("Smaller than Zero")
}
if (a.absoluteValue > 5) {
    println("Absolute is > 5")
}
like image 77
David Skrundz Avatar answered Oct 02 '22 21:10

David Skrundz


From The Swift Programming Language:

Extensions in Swift can:

  • Add computed properties and computed static properties
  • Define instance methods and type methods
  • Provide new initializers
  • Define subscripts
  • Define and use new nested types

Which means you can't add IBOutlets and other stored properties. If you really want to cheat, you can create global vars or a bookkeeping object which would allow you to query these vars or the object in order to add those properties (and have them be computed properties).

But it seems like it would go against the best practices. I would only do it if there's absolutely no other way.

like image 37
filcab Avatar answered Oct 02 '22 23:10

filcab