Skip to content

Instantly share code, notes, and snippets.

@chenshengzhi
Last active October 1, 2016 06:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save chenshengzhi/bc54e4d8f1013fc38a11 to your computer and use it in GitHub Desktop.
Save chenshengzhi/bc54e4d8f1013fc38a11 to your computer and use it in GitHub Desktop.
swift中的下划线(_)用法
//if循环中, 替代变量名来忽略对值的访问
let base = 3
let power = 10
var answer = 1
for _ in 1...power {
answer *= base
}
print("\(base) to the power of \(power) is \(answer)")
//switch的tuple, 匹配所有可能的值
let somePoint = (1, 1)
switch somePoint {
case (0, 0):
print("(0, 0) is at the origin")
case (_, 0):
print("(\(somePoint.0), 0) is on the x-axis")
case (0, _):
print("(0, \(somePoint.1)) is on the y-axis")
case (-2...2, -2...2):
print("(\(somePoint.0), \(somePoint.1)) is inside the box")
default:
print("(\(somePoint.0), \(somePoint.1)) is outside of the box")
}
//函数定义时, 如果你不想为第二个及后续的参数设置外部参数名, 用一个下划线(_)代替一个明确的参数名。
func someFunction(firstParameterName: Int, _ secondParameterName: Int) {
// function body goes here
// firstParameterName and secondParameterName refer to
// the argument values for the first and second parameters
}
someFunction(1, 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment