-1

I want to have a default property of UIImageView, which would be isFlipped. I am able to do it by subclassing UIImageView and adding one property isFlipped. But I want to user protocol and extensions for this , but it is crashing after sometime. Below is my code. How can I use it in right way? Thanks

import Foundation
import UIKit

protocol FlipImage {
    var isFlipped: Bool { get set }
}

extension UIImageView:FlipImage{
    var isFlipped: Bool {
        get {
            return  self.isFlipped
        }
        set {
            self.isFlipped = newValue
        }
    }
}
Vlad Pulichev
  • 3,162
  • 2
  • 20
  • 34
Sishu
  • 1,510
  • 1
  • 21
  • 48
  • What is the error message of "crash after sometime?" – Papershine May 19 '17 at 06:47
  • setter is calling again and again and it crashed. – Sishu May 19 '17 at 06:48
  • 1
    Your property getter and setter call themselves recursively, see for example http://stackoverflow.com/questions/25348049/override-a-setter-in-swift. – Note that you cannot add stored properties in class extension (unless you use associated objects). – Martin R May 19 '17 at 07:00

1 Answers1

3

As Martin R said you can't add stored properties to a class through class extensions. But you can use the objective C associated objects to do it via an extension

private var key: Void?

extension UIImageView {
    public var isFlipped: Bool? {
        get {
            return objc_getAssociatedObject(self, &key) as? Bool
        }

        set {
            objc_setAssociatedObject(self,
                                     &key, newValue,
                                     .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
}
adamfowlerphoto
  • 2,708
  • 1
  • 11
  • 24
  • Thanks!! it is working but I want to know how can I do using computed property using my code . If possible please tell me. – Sishu May 19 '17 at 07:15
  • If you want a computed and not stored property you don't need the objective C code. You can change get{} block to run your own code. If it is computed you would probably want to remove the set{} block. Not sure what you are trying to do so my response is fairly general – adamfowlerphoto May 19 '17 at 07:21