Home > Back-end >  SwiftUI getting rid of quotes in a string variable
SwiftUI getting rid of quotes in a string variable

Time:07-14

I have a string variable that gets populated from a text field. I want to remove any quotes a user might enter.

I've tried using replacingOccurrences in these examples.

print("Test A --------------------")
var testA = "\"Hello\""
var testAtrimmed = testA.replacingOccurrences(of: "\"", with: "")
print(testA)
print(testAtrimmed)
                                    
print("Test B --------------------")
var testB = move.moveAddy
var testBtrimmed = testB.replacingOccurrences(of: "\"", with: "")
print(testB)
print(testBtrimmed)
                                    
print("Test C --------------------")
var testC = String(move.moveAddy)
var testCtrimmed = testC.replacingOccurrences(of: "\"", with: "")
print(testC)
print(testCtrimmed)

The output of B and C retain their quotation marks. I've noticed their quotation marks look slightly different. I'm not sure if they are still text somehow but the moveAddy field of my struct is a String.

here is the console output

Anything I'm missing? Or any workarounds?

CodePudding user response:

Since the double quotes offered by Xcode and Device Keyboard are different, you can try this way to ensure that different types of double quotes from these different devices will be removed effectively.

import SwiftUI

struct Practice: View {
@State private var test = ""
@State private var test2 = "\"Hello\""
var body: some View {
    TextField("enter", text: $test)
    Button {
        test = test
                .replacing("\u{022}", with: "")
                .replacing("\u{201c}", with: "")
                .replacing("\u{201d}", with: "")
        test2 = test2
                .replacing("\u{022}", with: "")
                .replacing("\u{201c}", with: "")
                .replacing("\u{201d}", with: "")
        print(test)
        print(test2)
    } label: {
        Text("remove")
    }

}
}
  • Related