0

I've just migrated my code to Swift 4 and it added in lots of @objc code infront of several functions.

I think I get why after reading lots of posts on here, but my question is this - is there an alternative way of writing this code, that doesn't need to expose the Objective C runtime?

For example:

@objc func textFieldDidChange(textField: UITextField) {
 checkCode(textField.text ?? "")
}

Or:

@objc func hideKeyboard() {
 commentsBox.resignFirstResponder()
}

Or:

@objc func setDateChanged(_ sender:UIDatePicker) {
 setDate.text = dateFormatter.string(from: sender.date)
}

Is there a different way to write this code, that doesn't involve the @objc bit at the start?

Why? I like shorter, cleaner code (which is why I love Swift).

Many thanks in advance!

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Ben
  • 4,707
  • 5
  • 34
  • 55
  • 1
    The target action pattern requires the Obj-C runtime. If you want to expose multiple methods to Obj-C, you can group them together in a single `@objc extension`, compare https://stackoverflow.com/a/44391389/2976878 – Hamish Oct 12 '17 at 15:37
  • 1
    Go to your target's Build Settings and turn on `Swift 3 @objc inference`. This is the solution provided in in [SE-160](https://github.com/apple/swift-evolution/blob/master/proposals/0160-objc-inference.md) under the section *"Minimal" migration workflow* – Code Different Oct 12 '17 at 15:55
  • Thank you both - I was wondering if there was a pure swift way to do the same things as in the code above, rather than a build settings change / extension, but perhaps the lack of an answer has answered that question. – Ben Oct 12 '17 at 16:23
  • 1
    @Ben It depends on the API (for example, `Timer` allows for closure-based callbacks instead of target action). But ultimately, when working with frameworks written in Obj-C, you're likely going to have to do Obj-C interop at *some* point. You could always write a wrapper around (presumably?) `addTarget` that uses closures if you want (hiding the Obj-C interop in that wrapper). – Hamish Oct 12 '17 at 17:33
  • Thank you @Hamish - using my specific examples above then, could they be done in a different way avoiding the @objc? Or is it the case perhaps that UIKit is Obj-C based and therefore you can't get away from this? – Ben Oct 12 '17 at 18:49

0 Answers0