-1

Let's say I have the following strings:

"Chest Stretch (left)"
"Chest Stretch (right)"

How can I use SwiftUI to output only:

"Chest Stretch"

I thought this may be a possible duplicate of swift - substring from string.

However, I am seeking a way to do this inside var body: some View within an if conditional expression.

5
  • 2
    Could you explain why this is a SwiftUI question and why you need to do string manipulation inside a view? Please also add your own attempt at solving this. Commented Feb 28, 2022 at 14:07
  • For convenience - I could certainly handle this with a data structure inside my observed object or environment object and have the data ready by the time we're at the view. But, that gets into a larger design philosophy discussion. Even if its an antipattern to do this inside view, I am curious if it can be done. It's a huge convenience factor. Commented Feb 28, 2022 at 14:11
  • 2
    What are the criteria for trimming? Do you just want the first 13 characters? Delete anything in parentheses? Omit trailing words that aren't capitalized? Delete the last word? Commented Feb 28, 2022 at 14:12
  • @Caleb basically deleting the last parenthetical expression and removing the whitespace right before it. Commented Feb 28, 2022 at 14:13
  • So search from the right for the first open paren, and truncate the string up to that character? Commented Feb 28, 2022 at 15:12

1 Answer 1

3

A possible way is Regular Expression

let string = "Chest Stretch (left)"
let trimmedString = string.replacingOccurrences(of: "\\s\\([^)]+\\)", with: "", options: .regularExpression)

The found pattern will be replaced with an empty string.

The pattern is:

  • One whitespace character \\s
  • An opening parenthesis \\(
  • One or more characters which are not a closing parentheses [^)]+
  • and a closing parenthesis \\)

Or simpler if the delimiter character is always the opening parenthesis

let trimmedString = String(string.prefix(while: {$0 != "("}).dropLast())

Or

let trimmedString = string.components(separatedBy: " (").first!
Sign up to request clarification or add additional context in comments.

2 Comments

This is perfect
let trimmedString = String(string.prefix(while: {$0 != "("})).dropLast() Initializing a new string before dropping the last element is pointless. It will result in a substring. You probably meant String(string.prefix { $0 != "(" }.dropLast()) otherwise simply string.prefix { $0 != "(" }.dropLast() would suffice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.