NSString extension method does not call string extension method
I have an extension String
that defines test
. I also want to get test
functionality from NSString
. It's String.test
more complicated in real code . So instead of reusing it for NSString
, I cast str
in String
and invoke test
on it. I understand that it now str
has a type String
and String.test
will be called by returning String Test
.
However, it seems that str.test()
the call completes NSString.test
and I end up endless recursion until the stack overflows.
import Foundation
extension NSString {
func test() -> NSString {
let str = self as String
return str.test() as NSString
}
}
extension String {
func test() -> String {
return "String test"
}
}
let s: NSString = "test"
s.test()
source to share
I didn't really understand what it did, but from the looks of it Swift automatically exposes the extension methods you define on NSString
before String
. This way you can actually uninstall the version String
and just use NSString
. Alternatively, if you want to avoid line skewing in Obj-C to call your method, you can cast the implementation into a private global function (not an extension method) and call it from both implementations, for example:
import Foundation
private func stringTest(_ str: String) -> String {
return "String test"
}
extension NSString {
func test() -> NSString {
return stringTest(self as String) as NSString
}
}
extension String {
func test() -> String {
return stringTest(self)
}
}
source to share