Syntax-highlighting a String with Multiple Keys

I need to highlight a string with certain keys. The base string may contain one or more occurrences of a key.

Test 1: I use code based on this web site .

import SwiftUI

struct HighlightView: View {
	let baseText : String = "President's nearly $2 trillion proposed healthcare, climate, and social spending plan has been floundering for over a month since Mr. Williams came out against the bill in late December. That left the party with little to show after six months of negotiations with the conservative Democratic holdout.\n\nHe later left the door cracked open to future negotiations on a separate plan. Mr. Williams has spoken favorably about some chunks of the bill, including a program to establish universal pre-K and climate spending measures.\n\nMr. Williams wields outsized influence over the Democratic Party's agenda since the Senate is split 50-50 between both parties. Senate Democrats can't pass the package without his support, leaving them with no option but to eventually tailor a separate bill that addresses his concerns about its possible impact on the national debt and inflation.\n\nMr. Williams, meanwhile, appears to be focusing most of his time and energy leading a bipartisan group of senators working on election reform proposals including modernizing and updating the Electoral Count Act of 1887."
	let keys = ["Democratic", "Williams", "about"]
	var body: some View {
		ZStack {
			Text(baseText) { str in
				for i in 0..<keys.count {
					let key = keys[i]
					if let range = str.range(of: key) {
						str[range].foregroundColor = .pink
					}
				}
			}.foregroundColor(Color.gray).font(.system(size: 18.0))
		}
	}
}

extension Text {
	init(_ string: String, configure: ((inout AttributedString) -> Void)) {
		var attributedString = AttributedString(string) /// create an `AttributedString`
		configure(&attributedString) /// configure using the closure
		self.init(attributedString) /// initialize a `Text`
	}
}

The following screenshot shows the result. It handles multiple keys. But it highlights one occurrence for each key.

Test 2: I use code based on some web site, which I'm not permitted to show according to this system.

import SwiftUI

struct HighlightView2: View {
	let baseText : String = "President's nearly $2 trillion proposed healthcare, climate, and social spending plan has been floundering for over a month since Mr. Williams came out against the bill in late December. That left the party with little to show after six months of negotiations with the conservative Democratic holdout.\n\nHe later left the door cracked open to future negotiations on a separate plan. Mr. Williams has spoken favorably about some chunks of the bill, including a program to establish universal pre-K and climate spending measures.\n\nMr. Williams wields outsized influence over the Democratic Party's agenda since the Senate is split 50-50 between both parties. Senate Democrats can't pass the package without his support, leaving them with no option but to eventually tailor a separate bill that addresses his concerns about its possible impact on the national debt and inflation.\n\nMr. Williams, meanwhile, appears to be focusing most of his time and energy leading a bipartisan group of senators working on election reform proposals including modernizing and updating the Electoral Count Act of 1887."
	let keys = ["Democratic", "Williams", "about"]
	
	var body: some View {
		ZStack {
			ForEach(keys, id: \.self) { key in
				highlightedText(baseText: baseText, match: key, highlightColor: Color.orange)
					.foregroundColor(Color.gray).font(.system(size: 19.0))
			}
		}
	}
	
	func highlightedText(baseText: String, match: String, highlightColor: Color) -> Text {
		guard !baseText.isEmpty && !match.isEmpty else { return Text(baseText) }

		var result: Text!
		let components = baseText.components(separatedBy: match)
		for i in components.indices {
			result = (result == nil ? Text(components[i]) : result + Text(components[i]))
			if i != components.count - 1 {
				result = result + Text(match).foregroundColor(highlightColor)
			}
		}
		return result ?? Text(baseText)
	}
}

This one handles multiple occurrences. But I can only use one key at a time. The following screenshot shows the result.

Do you have a better idea in highlighting a string with multiple keys? Muchos thankos for reading.

Answered by Tomato in 703426022

I've ended up creating a UIViewRepresentable struct so that I can set an NSAttributedString object to a UILabel object.

Accepted Answer

I've ended up creating a UIViewRepresentable struct so that I can set an NSAttributedString object to a UILabel object.

Syntax-highlighting a String with Multiple Keys
 
 
Q