3 回答

TA貢獻(xiàn)1719條經(jīng)驗(yàn) 獲得超6個(gè)贊
創(chuàng)建擴(kuò)展時(shí),您還將經(jīng)常使用self,例如:
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
現(xiàn)在假設(shè)您要更改var結(jié)果本身,則必須使用mutating func進(jìn)行更改
var z = 3
println(z) // 3
現(xiàn)在讓它變異
z.squareMe()
println(z) // 9
//現(xiàn)在來(lái)看另一個(gè)使用字符串的示例:
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"
現(xiàn)在讓我們更改myString1
myString1.replicateMe(3)
println(myString1) // "AbcAbcAbc"
- 3 回答
- 0 關(guān)注
- 643 瀏覽
添加回答
舉報(bào)