What is "self" used for in Swift?
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"
Yes it is the same as this
in Java and self
in Objective-C, but with Swift, self
is only required when you call a property or method from a closure or to differentiate property names inside your code, such as initializers. So you can use almost all of your class components safely without using self
unless you are making the call from a closure.
“The self Property Every instance of a type has an implicit property called
self
, which is exactly equivalent to the instance itself. You use theself
property to refer to the current instance within its own instance methods.The
increment()
method in the example above could have been written like this:func increment() { self.count += 1 }
In practice, you don’t need to write
self
in your code very often. If you don’t explicitly writeself
, Swift assumes that you are referring to a property or method of the current instance whenever you use a known property or method name within a method. This assumption is demonstrated by the use ofcount
(rather thanself.count
) inside the three instance methods for Counter.The main exception to this rule occurs when a parameter name for an instance method has the same name as a property of that instance. In this situation, the parameter name takes precedence, and it becomes necessary to refer to the property in a more qualified way. You use the
self
property to distinguish between the parameter name and the property name.Here,
self
disambiguates between a method parameter calledx
and an instance property that is also calledx
:”
Excerpt From: Apple Inc. “The Swift Programming Language (Swift 2 Prerelease).”
This is how Ray Wenderlich recommends the use of self
in Swift for their tutorials:
Use of Self
For conciseness, avoid using self
since Swift does not require it to access an object's properties or invoke its methods.
Use self
when required to differentiate between property names and arguments in initializers, and when referencing properties in closure expressions as required by the compiler:
class BoardLocation {
let row: Int, column: Int
init(row: Int, column: Int) {
self.row = row
self.column = column
let closure = {
println(self.row)
}
}
}
And this is GitHub's recommendations on self
for their applications:
Only explicitly refer to
self
when required
When accessing properties or methods on self
, leave the reference to self
implicit by default:
private class History {
var events: [Event]
func rewrite() {
events = []
}
}
Only include the explicit keyword when required by the language — for example, in a closure, or when parameter names conflict:
extension History {
init(events: [Event]) {
self.events = events
}
var whenVictorious: () -> () {
return {
self.rewrite()
}
}
}
Rationale: This makes the capturing semantics of self stand out more in closures, and avoids verbosity elsewhere.