Search code examples
iosswiftmethod-swizzling

Swizzling in Swift with StaticString


I am trying to swizzle a Swift function that contains a StaticString parameter.

Here is what I tried:

let method = class_getClassMethod(self, original1)

class ABC {
  public static func updateABC(context: Int, str: StaticString) {
  }
}

However, this doesn't work, if I change the type of str to String, we can swizzle properly, anyone has chance to swizzle a function with StaticString type parameter could help out?

Thanks


Solution

  • StaticString is a value type so it has no Objective-C representation. Therefore it–and the declaration you use it in–are not exposed to Objective-C code or registered with the Objective-C runtime. String, on the other hand, is Objective-C compatible (it bridges to NSString) and so the declaration is Objective-C compatible.

    If you're going to swizzle a method, you need to mark it with dynamic to let the compiler know that it should always route calls through the Objective-C runtime, even in optimized code. Marking a function with dynamic will also cause the compiler to emit an error if your function is not Objective-C compatible, which could help you diagnose issues.