swift SWIFT中的下划线(_)用法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 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)

以上是关于swift SWIFT中的下划线(_)用法的主要内容,如果未能解决你的问题,请参考以下文章

swift_简单值 | 元祖 | 流程控制 | 字符串 | 集合

Swift 了解

Swift 1

下划线符号是不是会忽略或检查 Swift 中 switch 语句中的无效性?

Swift 提示:Initialization of variable was never used consider replacing with assignment to _ or removi

Swift:UIKit中Demo