0

I am creating a simple application meant to read messages from the local iMessage database on OSX (macOS 13.4). These messages are stored as NSMutableAttributedStrings, which I understand to be a type of NSAttributedString, and provided by the Foundation framework. Neither of these types seem available to my Swift program, leading me to wonder if the framework itself is missing.

A simple program simply declaring a variable of that type results in an error:

This builds and runs successfully:

print("Hello World\n")

This doesn't:

let s: NSAttributedString

Producing the error

main.swift:1:8: error: cannot find type 'NSAttributedString' in scope
let s: NSAttributedString
       ^~~~~~~~~~~~~~~~~~

4
  • 4
    Did you import Foundation? Commented Jun 26, 2023 at 13:06
  • @Sweeper I did not, and that indeed fixed the problem. Why the heck was that not mentioned/demonstrated on any of the approximately 951 search results I viewed when trying to solve this issue? Brand new to Swift and had no idea it was required. I'm doing all this on the CLI over SSH, maybe the GUI would have made this mistake apparent. Commented Jun 26, 2023 at 13:30
  • 1
    Swift is so embedded into the iOS development world, that it’s practically assumed UIKit or SwiftUI is used, both of which import foundation for you. Commented Jun 26, 2023 at 13:39
  • Having SwiftUI, UIKit, or Foundation "default" import is almost basic/implicitly done when creating a new file in iOS for instance. So it's often skipped from mention. But often, when an app doesn't recognize a class, it's a forgotten import issue (and that one, there are plenty on SO, not specifically to NSAttributedString, but usually to more "exotic" classes, since Foundation is almost every time there). Commented Jun 28, 2023 at 7:57

1 Answer 1

1

NSAttributedString is in the Foundation framework, as others have mentioned. It is not part of the Swift language.

When developing for iOS or Mac OS you almost always need to import either Foundation (Mac OS) or UIKit (iOS)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.