什么是“自我”用于Swift? [英] What is "self" used for in Swift?

查看:124
本文介绍了什么是“自我”用于Swift?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Swift的新手,我想知道 self 用于什么以及为什么。

I am new to Swift and I'm wondering what self is used for and why.

I已经在类和结构中看到了它,但我真的发现它们不是必需的,甚至没有必要在我的代码中提及它们。它们用于什么以及为什么?在什么情况下有必要使用它?

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?

我一直在阅读这个问题的许多问题和答案,但没有一个完全回答我的问题而且他们总是倾向于比较它与这个一样,在Java中,我对此并不熟悉。

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.

推荐答案

创建扩展时你也会经常使用自我,例如:

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

现在假设您要更改var结果本身
您必须使用变异函数来制作改变自己

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

现在允许改变它

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"

现在让我们更改myString1

now lets change myString1

myString1.replicateMe(3)

println(myString1)         // "AbcAbcAbc"

这篇关于什么是“自我”用于Swift?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆