String to NSString briding and objc method calling

Can somebody explain this documentation comment?

https://docs.swift.org/swift-book/LanguageGuide/StringsAndCharacters.html

NOTE

Swift’s String type is bridged with Foundation’s NSString class. Foundation also extends String to expose methods defined by NSString. This means, if you import Foundation, you can access those NSString methods on String without casting.

For more information about using String with Foundation and Cocoa, see Bridging Between String and NSString.

As I understood, this code regarding the doc should works:

import Foundation

class A {
    func doSome() {
        "".isEqual(to: "q")
    }
}

But it doesn't.

I've asked at stackoverflow but I didn't find a proper explanation.

This is probably a compiler bug when trying to resolve the method (it finds a method with the same name on String and so don't fallback to looking for NSString methods).

Other foundation methods without matching String method work as documented:

import Foundation

func foo() {
  "".caseInsensitiveCompare("q")
}

Thanks.

But the same behaviour appears for other methods.

For example, open var doubleValue: Double { get } of NSString doesn't exist for String too.

AFAIK, this methods (like the one having exact Swift counterpart) are not exposed to Swift String.

The set of methods available to Swift String are declared as extension to StringProtocol.

For doubleValue, you are supposed to use Double("") initialiser instead.

Please, improve the documentation. In the note it looks like, "Dear programmer, you can use objc methods as is". Now it confuses.

The documentation is correct as-is. It says methods are exposed, not all methods. Why would it expose methods that are duplicative?

I just tested what was inside the note. It was interesting to check it.There is no reason to use them. It confuses: you can use. You are right: there is no “you can use all “, but there is no “you can use a part of them” too.

The documentation is misleading.

"Foundation also extends String to expose methods defined by NSString. This means, if you import Foundation, you can access those NSString methods on String without casting.”

If “methods defined by NSString” really means “some methods defined by NSString” it should be corrected to say just that.

Jeremy

4 Likes

Yes, it is technically correct, but it is not clear (the proof is the existence of this thread).

Even correct documentation can be improved.

2 Likes