Skip to content

Instantly share code, notes, and snippets.

@0xWDG
Created April 1, 2020 12:55
Show Gist options
  • Save 0xWDG/429de9ab639ded1a980c6a3700ed8637 to your computer and use it in GitHub Desktop.
Save 0xWDG/429de9ab639ded1a980c6a3700ed8637 to your computer and use it in GitHub Desktop.
Swizzle

Swizzle 1 works (somehow)

The login() function is in the extension The fakeLogin() function is in the main class

Swizzle 2 does not work as expected

The login() function is in the main class The fakeLogin() function is in the extension

Swizzle 3 does work as expected

The dynamic login() function is in the main class The fakeLogin() function is in the extension

import Cocoa
import Foundation
// MARK: Swizzle
func swizzle(class kClass: AnyClass, oldSelector: Selector, with newSelector: Selector) {
guard let oldImplementation = class_getInstanceMethod(kClass, oldSelector) else {
print("Could not extract original implementation")
return
}
guard let newImplementation = class_getInstanceMethod(kClass, newSelector) else {
print("Could not find new implementation")
return
}
method_exchangeImplementations(oldImplementation, newImplementation)
}
// MARK: Test class 1
class testClass1 {
@objc func fakeLogin() -> Bool {
return true
}
}
extension testClass1 {
@objc func login() -> Bool {
return false
}
}
// MARK: Test class 2
class testClass2 {
@objc func login() -> Bool {
return false
}
}
extension testClass2 {
@objc func fakeLogin() -> Bool {
return true
}
}
// MARK: Test class 3
class testClass3 {
@objc dynamic func login() -> Bool {
return false
}
}
extension testClass3 {
@objc func fakeLogin() -> Bool {
return true
}
}
/**
* Test case 1.
* .
* The original login is in a extension.
* .
* Expected behaviour: [1] Welcome
* What happens: [1] Welcome
*/
// MARK: Shizzle 1
swizzle(
class: testClass1.self,
oldSelector: #selector(testClass1.login),
with: #selector(testClass1.fakeLogin)
)
// MARK: Test 1
if (testClass1().login()) {
print("[1] Welcome")
} else {
print("[1] Bad login")
}
/**
* Test case 2.
* .
* The fake login is in a extension.
* .
* Expected behaviour: [2] Welcome
* What happens: [2] Bad login
*/
// MARK: Shizzle 2
swizzle(
class: testClass2.self,
oldSelector: #selector(testClass2.login),
with: #selector(testClass2.fakeLogin)
)
// MARK: Test 2
if (testClass2().login()) {
print("[2] Welcome")
} else {
print("[2] Bad login")
}
/**
* Test case 3.
* .
* The login is dynamic.
* .
* Expected behaviour: [3] Welcome
* What happens: [3] Welcome
*/
// MARK: Shizzle 3
swizzle(
class: testClass3.self,
oldSelector: #selector(testClass3.login),
with: #selector(testClass3.fakeLogin)
)
// MARK: Test 3
if (testClass3().login()) {
print("[3] Welcome")
} else {
print("[3] Bad login")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment