0

I am a development novice and I am currently learning Swift 4. I am writing an egg timer app and I am confused. I have created a function to decrease the time within the scheduledTimer. However, it will not let me compile and build until I create the decreaseTimer() function with @objc.

Why is this? I am confused lol. My code is working but just want to know how ?

Here is my code:

import UIKit

class ViewController: UIViewController {

var timer = Timer()

var time = 210

@objc func decreaseTimer() {

    if time > 0 {

    time -= 1

    timerLabel.text = String(time)
    } else {

        timer.invalidate()
    }

}


@IBOutlet weak var timerLabel: UILabel!

@IBAction func play(_ sender: Any) {

    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.decreaseTimer), userInfo: nil, repeats: true)

}

Any advice would be most appreciated. Thank you

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Ju_
  • 55
  • 1
  • 1
  • 9
  • 3
    Possible duplicate of [How can I deal with @objc inference deprecation with #selector() in Swift 4?](https://stackoverflow.com/questions/44390378/how-can-i-deal-with-objc-inference-deprecation-with-selector-in-swift-4) – LinusGeffarth Aug 02 '18 at 09:56
  • 1
    Please read [SE-0160 Limiting @objc inference](https://github.com/apple/swift-evolution/blob/master/proposals/0160-objc-inference.md) – vadian Aug 02 '18 at 10:00

1 Answers1

3

The selector is essentially a name of function that is dynamically searched on the target object. The problem is that Swift does not provide any reflection API to search for methods by name and then call then dynamically, that can be done only in Objective-C. Therefore, you have to make the method accessible from Objective-C.

Sulthan
  • 128,090
  • 22
  • 218
  • 270
  • Thanks for your answer. That does make sense. However, I have seen similar code run and work in Swift 3 without using @objc. Has something changed since version 3? – Ju_ Aug 02 '18 at 09:55
  • @Jay Yes, In Swift 3 all `NSObject` subclasses had methods that were `@objc` automatically, including all `UIViewController` and similar. – Sulthan Aug 02 '18 at 09:57
  • Ah okay, that explains it. I just read SE-0160 and although I don't understand all of it, I understand enough :). Thanks again Sulthan. – Ju_ Aug 02 '18 at 10:04