Search code examples
iosswiftself

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?

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.


Solution

  • 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 let's 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 let's mutate it

    z.squareMe()
    
    println(z)  // 9
    

    // now let's 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 let's change myString1

    myString1.replicateMe(3)
    
    println(myString1)         // "AbcAbcAbc"