Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String extension that modify self in swift

Tags:

ios

swift

I have written my fist extension in swift.
Here is code:

extension String
{
    // add padding
    // source: http://zh-wang.github.io/blog/2014/09/25/learning-swift-part-6/
    func alignRight(count: Int, pad: Character) -> String
    {
        let amountToPad = count - countElements(self)
        if amountToPad < 1 {
            return self
        }
        let padString = String(pad)
        var string = self
        for _ in 1...amountToPad {
            string = padString + string
        }
        return string
    }
}

This is working fine, I use it like this:

let a = "ddd"
let b = a.alignRight(5,  pad: "0") //  b is 00ddd

I would like to know is it possible to do it like this

var a = "ddd"
a.alignRight(5,  pad: "0") //  a is 00ddd

So I would like to make extension that is changing string, not making new one.
I have a problem because I can not do self = "something" in my extension.

Is this normal or I am missing something ?

like image 424
WebOrCode Avatar asked Nov 30 '14 15:11

WebOrCode


1 Answers

You should use the mutating keyword.

mutating func alignRight(count: Int, pad: Character) {
// self = something works
}

See the extensions' documentation for more information.

like image 62
DCMaxxx Avatar answered Nov 11 '22 07:11

DCMaxxx