Last active
May 11, 2021 20:00
-
-
Save GeorgeElsham/64189213ecfdbcd25e824109909c2b22 to your computer and use it in GitHub Desktop.
Gets underlying string from SwiftUI's `Text`. Why would you want this? Who knows...
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
import SwiftUI | |
extension Text { | |
func readStrings() -> [String] { | |
let mirror = Mirror(reflecting: self) | |
if let keyMirror = mirror.descendant("storage", "anyTextStorage", "key") { | |
// Only contains one string | |
let newMirror = Mirror(reflecting: keyMirror) | |
guard let str = newMirror.descendant("key") as? String else { return [] } | |
guard let arguments = newMirror.descendant("arguments") else { return [] } | |
let argumentMirror = Mirror(reflecting: arguments) | |
// Arguments from string interpolation | |
let args = argumentMirror.children.compactMap { arg -> Any? in | |
let argMirror = Mirror(reflecting: arg.value) | |
return argMirror.descendant("storage", "value", ".0") | |
} | |
guard let args = args as? [CVarArg] else { return [] } | |
let formattedString = String(format: str, arguments: args) | |
return [formattedString] | |
} else { | |
// Contains two strings | |
var allStrings: [String] = [] | |
if let firstText = mirror.descendant("storage", "anyTextStorage", "first") as? Text { | |
allStrings.append(contentsOf: firstText.readStrings()) | |
} | |
if let secondText = mirror.descendant("storage", "anyTextStorage", "second") as? Text { | |
allStrings.append(contentsOf: secondText.readStrings()) | |
} | |
return allStrings | |
} | |
} | |
} | |
let meaningOfLife = true ? 42 : 0 | |
let string1 = Text("Hello world! \(meaningOfLife)...").readStrings() | |
let string2 = (Text("Hello") + Text(" world") + Text("! \(meaningOfLife)\("...")")).readStrings() | |
print(string1) // Prints: ["Hello world! 42..."] | |
print(string2) // Prints: ["Hello", " world", "! 42..."] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment