Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to NSString briding regarding documentation doesn't work

Tags:

swift

Documentation issue:

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.

The question is what did they mean? Should this feature work?

import Foundation

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

It doesn't compile!

Only this works:

import Foundation

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

but as? is a casting operation

and without import Foundation NSString isn't defined.

like image 720
Vyacheslav Avatar asked Dec 01 '25 03:12

Vyacheslav


1 Answers

A bridge cast is as without question or exclamation mark.

("" as NSString).isEqual(to: "q")

And an optional bridge cast is

let string : String? = ""
(string as NSString?)?.isEqual(to: "q")
like image 103
vadian Avatar answered Dec 03 '25 03:12

vadian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!