Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift - Remove white spaces from var(UITextField input) doesn't work

I'm new to swift, but from ObjectiveC background, I tried to get an input from textfield into a var, on a button click.

Now, when I tried to remove blank space using "stringByTrimmingCharactersInSet" and so many other options, it's not working. Here is my code,

    var someVariable = urlInputComponent.text!
    if someVariable.containsString(" "){
        someVariable = someVariable.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
        print(someVariable)

    }

I also tried by assigning the result to a new var,

        let trimmed: String = someVariable.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
        print(trimmed)

but still couldn't remove the whitespace. My guess is I'm confusing with the "Unwrapped value" concept, it'll be really helpful if someone could help me out. Thanks!

like image 353
Rajesh S Avatar asked Dec 18 '22 17:12

Rajesh S


1 Answers

try the alternate way

 urlInputComponent.text! = urlInputComponent.text!.stringByReplacingOccurrencesOfString(" ", withString: "")

or else try this

let trimmed = "".join(urlInputComponent.text!.characters.map({ $0 == " " ? "" : String($0) }))
 print (trimmed)
like image 199
Anbu.Karthik Avatar answered Dec 28 '22 22:12

Anbu.Karthik