I am looking for ways to swizzle Swift.print function. Overriding it is not an option, as it may get bypasses if you use Swift.print(:)
The selector does not recognise the identifier:
@objc class func printSwizzle() {
guard let instance = class_getInstanceMethod(self, #selector(print(separator:terminator:))),
let swizzleInstance = class_getInstanceMethod(self, #selector(swizzlePrint(separator:terminator:))) else { return }
method_exchangeImplementations(instance, swizzleInstance)
}
Is that even possible? As swizzling is an obj-c runtime feature.

Method swizzling is an Objective-C feature that enables you to exchange implementation of a method at runtime. For that, you need an
@objcobject that inherits fromNSObject. And you need a method.Swift.printis not a method. It's a function declared in theSwiftmodule. We can say it's global but it's not really global. It's defined inside moduleSwiftwhich is imported automatically to every Swift code, therefore you can use it without theSwift.prefix.In summary, there is no way to swizzle
Swift.print.What you can do is to hide that function using your own implementation, that is, if you declare a function with the same name in your own module, then when
printis used, the compiler will prefer your function instead because functions in the current module are preferred over functions in other modules (includingSwift.module).You can any logic you want in there.
It's actually very common to use this to remove logging from production, e.g.:
See Remove println() for release version iOS Swift for more details.
Essentially, you could hide the whole
Swiftmodule by redeclaring it inside your module, e.g. as anenum, therefore disabling calls toSwift.print:However, I would generally advise against this because it will be hard to solve any naming conflicts with the standard library inside the
Swift.module.In general, I would advise to implement your custom logging system and enforce its usage by other means, e.g. code reviews or linting rules (e.g. swiftlint).