0

I'm trying to figure out a way to write Swift equivalents to Kotlin's apply and also methods. I think I know how I'm going to implement it, but was wondering whether there is a shortcut to applying it to all or most of the main uikit classes.

Basically, I want something like:

extension ____ {
    func apply(() -> void) {

    }

    func also(() ->  void) {

    }x
}

to be available to all classes.

  • 1
    You could extend NSObject if that helps. Or AnyObject, see this [post](https://stackoverflow.com/a/31988258/1649241) – Brooketa Jan 02 '19 at 20:46

2 Answers2

2

Not to all UIKit classes in one step, but you can simplify things a little by applying it to classes that others inherit from. For example if you add an extension to UIResponder, it gets inherited by a lot of other classes, including UIView and everything that inherits from that, plus UIViewController and all of its descendant classes. Really that's pretty much everything that shows on the screen. Beyond that, you can pick off classes like UIImage and UIColor, if they make sense.

Tom Harrington
  • 69,312
  • 10
  • 146
  • 170
  • NSObject is even higher – impression7vx Jan 02 '19 at 20:50
  • Why wouldn’t extending NSObject work? Can you explain? Thx – matt Jan 02 '19 at 20:51
  • @impression7vx Yes but the question was about UIKit. Using `NSObject` will involve many, many classes that aren't in UIKit. – Tom Harrington Jan 02 '19 at 20:51
  • is there some source that I could refer to to see how everything is connected? There has to be something better than just going to every classes individually in the docs – satoshiMotoMoto Jan 02 '19 at 20:52
  • Ok but he didn’t say “all or most of the main uikit classes but no others”. – matt Jan 02 '19 at 20:53
  • @satoshiMotoMoto I don't know of one in Apple's docs, but if you Google "UIKit class hierarchy" you'll find some useful diagrams. For example: http://ios-funda.blogspot.com/2015/04/uikit-class-hierarchy.html – Tom Harrington Jan 02 '19 at 20:57
  • @matt True but it's always best to limit the effect of an extension to classes where you want it to apply, instead of letting it apply to all kinds of irrelevant stuff. – Tom Harrington Jan 02 '19 at 20:59
  • Is there a way to apply it across all classes? Including ints, strings etc – satoshiMotoMoto Jan 02 '19 at 21:23
  • I like my answer better. It’s more extendable. Pun intended – impression7vx Jan 02 '19 at 21:23
  • Extending `NSObject` is a bad idea unless there's some compelling reason to need the extension on pretty much everything on iOS. You hit all of Foundation, UIKit, and dozens of other frameworks in one shot. If you don't actually need all of that, you're polluting the global namespace with unnecessary code. – Tom Harrington Jan 02 '19 at 23:01
0

Just apply the extension to NSObject.

https://developer.apple.com/documentation/objectivec/nsobject

Not sure if it is every class, but somewhere to start.

impression7vx
  • 1,728
  • 1
  • 20
  • 50