I finally used method-swizzling
It was long ago when I wrote an article about method swizzling (To swizzle or not to swizzle?) in which I was describing how it works in Objective-C and whether I would use it or not.
Frankly, my experience with method swizzling was experimental and I never worked on a project that was using it. Also, I found it amusing that I still agree with myself from 4 years ago (a rare occasion), that I would never use it in a commercial project.
Last week there was a request from the design team that one developer from our team, should go throughout the app and log font family, weight, and size for every UILabel
. I know you can't even think the hustle, going from screen to screen, trying to find all the possible scenarios that a UILabel
is shown, and then going back to source code to find what font was used and log it.
My software developer instincts kicked in. I would rather spend hours trying to solve this problem with code than doing this task manually. "I wouldn't be a software developer if I wanted to do such boring tasks", I thought to myself.
But, sometimes doing a boring task is inevitable, so I gave myself one hour to come back with a "code" solution otherwise I will start the task manually.
And as Bill Gates said: "I choose a lazy person to do a hard job. Because a lazy person will find an easy way to do it.", I came up with the following solution, because I am becoming lazy when there is a boring task!
extension UILabel {
static let classInit: Void = {
guard let originalMethod = class_getInstanceMethod(UILabel.self, #selector(setter: UILabel.text)),
let swizzledMethod = class_getInstanceMethod(UILabel.self, #selector(setter: UILabel.swizzledText))
else { return }
method_exchangeImplementations(originalMethod, swizzledMethod)
}()
@objc var swizzledText: String? {
get {
text
}
set {
self.swizzledText = "\(self.font.fontName) \(self.font.pointSize)"
}
}
}
What this snippet of code does, is replacing the original text of each label with the font name(which includes weight) and size. So, you make a build, send it to the team and anyone can browse the app and log all the necessary details. Simple as that.
The purpose of this article is to encourage the exploration of "different" concepts, even when you think that you would never use them. You never know when they might come in handy.
Happy coding!!