0

I have the following code:

func enableDelaysContentTouchesIncudlingSubviews(enable: Bool) {
    self.setDelaysContentTouches(enable, forObject: self)
    for obj: AnyObject in self.subviews {
        self.setDelaysContentTouches(enable, forObject: obj)
    }
}

private func setDelaysContentTouches(var value: Bool, var forObject obj: AnyObject) {
    if obj.respondsToSelector("setDelaysContentTouches:") {
        obj.delaysContentTouches = value
    }
}

On the second function, the line obj.delaysContentTouches = value raises the following error: Cannot assign to property: 'obj' is immutable

I don't understand the reason since obj is declared as a var parameter. Therefor it should be mutable in my understanding.

Could somebody please explain me the reason and also provide a workaround.

Thanks in advance!

danielgehr
  • 127
  • 1
  • 6

1 Answers1

0

My guess is it's an issue of AnyObject technically being a protocol

Assuming you're working in a view, maybe try something along these lines:

func enableDelaysContentTouchesIncudlingSubviews(enable: Bool) {
    self.setDelaysContentTouches(enable, view: self)
    self.subviews.forEach({setDelaysContentTouches(enable, view: $0)})
}

private func setDelaysContentTouches(enable: Bool, view: UIView) {
    if let viewAsScrollview = view as? UIScrollView {
        viewAsScrollview.delaysContentTouches = enable;
    }
}

This is a much swiftier way of doing things, more clear, and doesn't use "respondsToSelector"

More info, and possibly a more direct answer about respondsToSelector in swift here

Community
  • 1
  • 1
GetSwifty
  • 7,568
  • 1
  • 29
  • 46
  • Yeah you're right, he's trying to access delaysContentTouches on AnyObject while that is a protocol and doesn't even have the delaysContentTouches property. Only a UIScrollView class or subclass has that property. How he does not even receive any errors astonishes me. XCode is probably giving the wrong error too. – Orion Mar 17 '16 at 16:29
  • nice, this code works and solved my problem. thanks for the "swiftification" :-) – danielgehr Mar 17 '16 at 16:43