Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift. Replacing a variable's value using an extension function

Tags:

swift

I want to make a function to change the original value of my variable. for example

class Something {
    var name:String = "   John Diggle   "
    name.trim()
    print(name)
    // prints out "   John Diggle   "

    // what I wanna do is to make it so that I don't do this
    name = name.trim()
    print(name)
    // prints out "John Diggle"
}




extension String {
   func trim() -> String{
       return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
   }
}

is there a way to change the value of a variable inside a function without doing name = name.trim() ?

like image 846
Zonily Jame Avatar asked Dec 24 '22 00:12

Zonily Jame


1 Answers

Maybe something like this?

extension String {
    mutating func trim() {
        self = self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
    }
}

Then you can use it as name.trim()

like image 59
Tj3n Avatar answered Mar 06 '23 02:03

Tj3n