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 ?
You should use the mutating
keyword.
mutating func alignRight(count: Int, pad: Character) {
// self = something works
}
See the extensions' documentation for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With