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 关注
- 604 浏览
添加回答
举报