Lucas Martin Calderon Lucas Martin Calderon - 4 months ago 7
iOS Question

What is "self" used for in Swift?

I am new to Swift and I'm wondering what "self" is used for and why.
I have seen it in classes and structures but I really don't find them essential nor necessary to even mention them in my code. What are they used for and why? In what situations it's necessary to use it?
PD:I have been reading lots of questions and answers for this question but none of them fully answers my questions and they always tend to compare it with "this" as in Java, with which I'm not familiar whatsoever.

Answer

You will also use self a lot when creating your extensions, example:

extension Int {
    func square() -> Int {
        return self * self
    }

    // note: when adding mutating in front of it we don't need to specify the return type
    // and instead of "return " whatever
    // we have to use "self = " whatever

    mutating func squareMe() {
        self = self * self
    }
}
let x = 3
let y = x.square()  
println(x)         // 3
printlx(y)         // 9

now lets say you want to change the var result itself you have to use the mutating func to make change itself

var z = 3

println(z)  // 3

now lets mutate it

z.squareMe()

println(z)  // 9

// now lets see another example using strings :

extension String {
    func x(times:Int) -> String {
        var result = ""
        if times > 0 {
            for index in 1...times{
                result += self
            }
            return result
        }
        return ""
    }

    // note: when adding mutating in front of it we don't need to specify the return type
    // and instead of "return " whatever
    // we have to use "self = " whatever

    mutating func replicateMe(times:Int){
        if times > 1 {
            let myString = self
            for index in 1...times-1{
                self = self + myString
            }
        } else {
            if times != 1 {
                self = ""
            }
        }
    } 
}


var myString1 = "Abc"
let myString2 = myString1.x(2)

println(myString1)         // "Abc"
println(myString2)         // "AbcAbc"

now lets change myString1

myString1.replicateMe(3)

println(myString1)         // "AbcAbcAbc"