Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString extension method doesn't call String extension method

I have an extension on String that defines test. I also want to be able to get test's functionality from NSString. In the real code String.test is more complex. So rather than re-implementing it for NSString I cast str to String and call test on it. My understanding here is that now str is of type String and String.test will be invoked, returning String Test.

However, it seems that str.test() winds up calling NSString.test and I wind up with unending 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()
like image 991
Alex Bollbach Avatar asked Oct 17 '22 11:10

Alex Bollbach


2 Answers

Change your first function to:

func test() -> NSString {
    let str = self as String
    return ("" + str.test()) as NSString
}

which should get you going...

then submit a bug report.

HTH

like image 136
CRD Avatar answered Oct 21 '22 00:10

CRD


extension NSString {
    func test() -> NSString {
        let str = (self as String).test()
        return str as NSString
    }
}
like image 43
Fatih Aksu Avatar answered Oct 21 '22 01:10

Fatih Aksu