在Swift语言中,有很多默认值,这里将常用的总结,欢迎补充。
func swap(var a: Int, var b: Int){
let c = a
a = b
b = c
}
var a = 3
var b = 2
swap(a, b) // a = 3, b = 2func swap(inout a: Int, inout b: Int){
let c = a
a = b
b = c
}
var a = 3
var b = 2
swap(a, b) // a = 2, b = 3class StepCounter {
var totalSteps: Int = 0
willSet(newTotalSteps){
println("About to set totalSteps to \(newTotalSteps)") // you can use newValue if you does not set a name with newTotalSteps
}
didSet{
if totalSteps > oldValue {
println("Added \(totalSteps - oldValue) steps")
}
}
}
let stepCounter = StepCounter() // no output since it is the initialiser, not change the value.
stepCounter.totalSteps = 200 // print both the willSet‘s and didSet‘s output.class Optional{
var a: Int?
var b: Int
}a = 10
// optional binding.
if let c = a {
println("\(c)")
} else {
println("a is nil")
}
// forced unwrapping, might cause an runtime error if a is nil.
let d = a!struct Circle {
var radius: Float
var diameter: Float {
get{
return 2.0 * radius
}
set{
radius = newValue / 2.0
}
}
} 如上代码中,没有设置参数名,使用默认的值:newValue。为了便于理解,可以设置新的参数名。struct Circle {
var radius: Float
var diameter: Float {
get{
return 2.0 * radius
}
set(newDiameter){
radius = newDiameter / 2.0
}
}
}Swift——(五)Swift中的那些默认值,布布扣,bubuko.com
原文地址:http://blog.csdn.net/twlkyao/article/details/33799353