Search code examples
iosswiftiphonestringcocoa

Why does swift say that when I don't import the cocoa framework, there are no member functions of the String?


If you run the following function in vs code, you will get a compilation error that the addingPercentEncoding function does not exist, but if you import the cocoa framework, it will run normally. What's the difference between the two?

enter image description here

enter image description here


Solution

  • The addingPercentEncoding(withAllowedCharacters:) function is a part of the Foundation framework in Swift, which provides a set of common data types and APIs for working with strings, dates, URLs, and more. The Cocoa framework, on the other hand, is a higher-level framework that builds on top of Foundation, and provides additional functionality for developing macOS and iOS applications.

    When you import Cocoa, you are also importing Foundation, because Cocoa depends on Foundation. This is why you are able to use the addingPercentEncoding(withAllowedCharacters:) function without any compilation errors.