What Is "Self" Used for in Swift

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"

What is the purpose of self in Swift

self is a reference to the current instance of the class in which the code is running.

In both the init method and the paint method, it allows you to specify that you wish to set the member variable named color using the value passed in the parameter to the method that is also called color.

The paint method cannot reference the parameter passed to init at all (nor vice versa).

So, in your sample code, both methods set the color of the object to some specified value passed in to the method as a parameter.

The init method sets an initial color for the object.

The paint method then allows you to change the color of the object from that initial color.

This might be clearer if the parameters were simply named differently, e.g.:

required init(initialMake: String, initialColor: String) {
self.make = initialMake
self.color = initialColor
}

func paint(newColor: String) {
self.color = newColor
}

In this case, since the functions are member methods, the self is now entirely optional since the compiler knows that color now can only mean the member called color since there is no other variable or parameter with that name, i.e. the paint method could be written simply as:

func paint(newColor: String) {
color = newColor
}

and this would have the exact same behaviour.

However, some people prefer to keep the self prefix for clarity, even where it isn't strictly required since as well as making the intent clear it can help avoid accidental mistakes if variables or member names are changed.

What is `self` in swift?

self is a keyword and normally you cannot use keywords and reserved words in places outside their context. However, that sometimes creates problems. For that reason there is a special syntax to make the keyword to be a normal identifier, e.g.:

enum MyEnum: String {
case `default`
}

(also see Swift variable name with ` (backtick))

Historically self was not allowed as as a constant name inside guard-let-else and therefore backticks were commonly (ab)used.
They are no longer needed since Swift 4.2.

The code will still work correctly since you can wrap any identifier in backticks and it will just be a normal identifier.

self' used before all stored properties are initialized in struct

Instead defining your getRandom as an instance method, define it as a static one, then reference it by a type name (CurrentData) or Self

struct CurrentData {
var size: (x: Int, y: Int)
var location: (x: Int, y: Int)

init(size: (x: Int, y: Int)) {
self.size = size
location = (Self.getRandom(size.x), Self.getRandom(size.y))
}

private static func getRandom (_ value:Int) -> Int {
Int.random(in: 0...value-1)
}
}

Other solution is to define your locationproperty as a lazy one, then the self is accessible and the location will be executed only once and after being called in the code.

struct CurrentData {
var size: (x: Int, y: Int)
lazy var location: (x: Int, y: Int) = {
(getRandom(size.x), getRandom(size.y))
}()

init(size: (x: Int, y: Int)) {
self.size = size
}

private func getRandom (_ value:Int) -> Int {
Int.random(in: 0...value-1)
}
}

Is there a tangible benefit to using self outside of closures?

There is.

In the examples you provided it makes no difference, it's purely a style choice. Some people might like it since it explicitly tells you you're modifying self, personally I think it looks cleaner without.

Where it matters is when you have a local variable with the same name. Let's say you have a class that has a var count: Int property. Then, in one of your methods, you declare a new variable with the same name.

The local variable will be used whenever you type count, so if you want to modify or read the object's variable, you'll need to use self.

Some examples where it makes a difference:

guard let count = calculateCount() as? Int else { return }
self.count = count

init(count: Int) {
self.count = count
}

func updateCount(_ count: Int) {
self.count = count
}

In Swift, what is the difference between the two different usages of self?

Your first usage of self as a prefix is a reference to the instance of the class that contains the method that is currently being invoked. In the second usage, self is referring to a type as a value, in this case UITableViewCell.self refers to the UITableViewCell type

In Swift 3, what object does self refer to in this instance

When you call an object's (non-static/class) function, you call it like this:

obj.function()

Inside of function(), self refers to the object it was called on (so obj in this case). self is like an automatic variable you get made for you to make it convenient to refer to the target of the function call.

In your case, it's pretty clear that this code is from a ViewController of some sort. That VC has an imageView property that represents (probably) a UIImageView in the VC. I'm guessing your code is inside a function that is either called by viewDidLoad (or similar) or perhaps it's the target of a button tap.

When those functions are called, self will refer to the ViewController object that the function was called on.



Related Topics



Leave a reply



Submit