3 回答

TA貢獻1719條經驗 獲得超6個贊
創建擴展時,您還將經常使用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
現在假設您要更改var結果本身,則必須使用mutating func進行更改
var z = 3
println(z) // 3
現在讓它變異
z.squareMe()
println(z) // 9
//現在來看另一個使用字符串的示例:
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
myString1.replicateMe(3)
println(myString1) // "AbcAbcAbc"
- 3 回答
- 0 關注
- 647 瀏覽
添加回答
舉報