easiwriter
easiwriter

Reputation: 73

How to I convert NSAttributedString to AttributedString

I am using Xcode 16.1 and attempting to convert an NSAttributedString to an AttributedString but the compiler doesn't recognise the init:

Here's my code:

  let ns = NSAttributedString(string: "Fred")
  let s = AttributedString(ns)

The compiler gives the error: Cannot convert value of type 'NSAttributedString' to expected argument type 'NSCoder'. The correct initialiser doesn't appear in autocomplete.

It works OK in playground and a new project, so I'm guessing something must be wrong with my project. I've tried all the usual cleanup actions.

Upvotes: 0

Views: 245

Answers (1)

K.pen
K.pen

Reputation: 189

enter image description here

Ensure you're using Swift 5.5 or newer, as AttributedString was introduced in Swift 5.5.

Extension Code

extension NSAttributedString {
    func toAttributedString() -> AttributedString? {
        return AttributedString(self)
    }
}

Usage

struct ContentView: View {
    var body: some View {
        let nsAttributedString = NSAttributedString(string: "Hello, Xcode 16!", attributes: [
            .foregroundColor: UIColor.red,
            .font: UIFont.boldSystemFont(ofSize: 18)
        ])

        if let attributedString = nsAttributedString.toAttributedString() {
            Text(attributedString)
        } else {
            Text("Failed to convert NSAttributedString")
        }
    }
}   

Upvotes: 0

Related Questions