-3

As I referred here, there is no @property or @synthesise directive present in swift.

Then,

1] how the setter and getter will be added by compiler?

2] If I have a object, how to write our own setter and getter methods?

I am new to Can any one explain with example?

//EDIT :

Before down voting, please let me show as in the Apple documentation.

@property (getter=isFinished) BOOL finished; will override getter method.

In the same way how can I achieve in Swift?

For in the below example, how to make getter as isFinished

class CarPaint : NSObject {

    var finished:Bool = Bool();

    func getCarDoorColor() -> UIColor {

        if finished { //instead here I want to `isFinished`
            return UIColor.whiteColor()
        }

        return UIColor.brownColor()

    }

}
jax
  • 33
  • 1
  • 5
  • 1
    Have you ever looked at Swift documentation at all? Ex: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html – Ozgur Vatansever Apr 27 '16 at 06:33
  • @ozgur Yes, I read it again ! But all the examples (Rect, Point) are gave based on structure. I am not able to find the custom method/ functions to implement getter and setter. – jax Apr 27 '16 at 06:42

2 Answers2

3

You can change how a property is accessed in Swift like this:

private var _someInt: Int = 0
var someInt: Int {
    get {
        return _someInt
    }
    set(newValue) {
        _someInt = newValue
    }
}

In this example, we're using a private variable to store our value, and using the get/set closures to access that variable instead. As is, this isn't very useful, but it can be useful in other cases, such as if you want to access the variable of another object as if it were a property of this one.

Dave Wood
  • 13,143
  • 2
  • 59
  • 67
0

Answering the 2nd part your of question, there is no named getter in Swift till now.

@property (getter=isFinished) BOOL finished;

Apple suggests the above Objective-C equivalent code in Swift in their migration documentation

var _finished:Bool = false // finished boolean variable.

var finished:Bool { //Getter(custom) and Setter for finished variable.

    @objc(isFinished) get {
        return self._finished
    }
    set(newValue){
        _finished = newValue
    }
}

Only way to make work around of getter self.isFinished()

func isFinished() ->  Bool {
    return _finished;
}

I hope you got the solution.

byJeevan
  • 3,728
  • 3
  • 37
  • 60