Search code examples
swiftmacosnsattributedstring

What is needed in order to use NSAttributedString in a Swift application?


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
       ^~~~~~~~~~~~~~~~~~


Solution

  • 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)