@Rookie
2019-09-23T08:04:34.000000Z
字数 1212
阅读 1295
swift学习
通过使用下划线能够提高数字字面量的可读性,比如:
let paddedDouble = 123.000_001let oneMillion = 1_000_000
当我们使用元组时,假设有的元素不须要使用。这时能够使用下划线将对应的元素进行忽略,比如:
let http404Error = (404, "Not Found")let (_, errorMessage) = http404Error
代码中。仅仅关心http404Error中第二个元素的值。所以第一个元素能够使用下划线进行忽略。
let base = 3let power = 10var answer = 1for _ in 1...power {answer *= base}
有时候我们并不关心区间内每一项的值,能够使用下划线来忽略这些值。
class Counter {var count: Int = 0func incrementBy(amount: Int, numberOfTimes: Int) {count += amount * numberOfTimes}}
在上面的代码中,方法incrementBy()中的numberOfTimes具有默认的外部參数名:numberOfTimes,假设不想使用外部參数名能够使用下划线进行忽略,代码能够写为(只是为了提高代码的可读性,一般不进行忽略):
class Counter {var count: Int = 0func incrementBy(amount: Int, _ numberOfTimes: Int) {count += amount * numberOfTimes}}
func join(s1: String, s2: String, _ joiner: String = " ") -> String {return s1 + joiner + s2}// call the function.join(s1: "hello", s2: "world", joiner: "-")
假设不想使用默认外部參数名,能够进行例如以下改动:
func join(s1: String, s2: String, _ joiner: String = " ") -> String {return s1 + joiner + s2}// call the function.join("hello", "world", "-")
