Last active
May 2, 2024 03:12
-
-
Save davidbalbert/2b47871d4d942a2431e3c33891fbcfe9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ContentView.swift | |
// UnicodeExplorer | |
// | |
// Created by David Albert on 5/1/24. | |
// | |
import SwiftUI | |
struct ContentView: View { | |
@State var text: String = "" | |
var body: some View { | |
VStack { | |
Form { | |
TextField("Text", text: $text) | |
LabeledContent("Code points") { | |
VStack(alignment: .leading, spacing: 5) { | |
ForEach(Array(text.unicodeScalars.enumerated()), id: \.0) { (i, s) in | |
if let name = s.properties.name { | |
return Text("\(i). \(String(format: "U+%04X", s.value)) \(name)") | |
} else { | |
return Text("\(i). <?>") | |
} | |
} | |
} | |
} | |
} | |
Spacer() | |
} | |
.padding() | |
.onChange(of: text) { | |
let regex = /\\u{([0-9a-fA-F]+)}/ | |
if !text.contains(regex) { | |
return | |
} | |
let newText = text.replacing(regex) { match in | |
let codePoint = Int(match.output.1, radix: 16)! | |
if let scalar = Unicode.Scalar(codePoint) { | |
return String(scalar) | |
} | |
return String(match.output.0) | |
} | |
text = newText | |
} | |
} | |
} | |
#Preview { | |
ContentView() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment