[关闭]
@Rookie 2019-09-23T08:04:34.000000Z 字数 1212 阅读 948

Swift下划线作用

swift学习


1.格式化数字字面量

通过使用下划线能够提高数字字面量的可读性,比如:

  1. let paddedDouble = 123.000_001
  2. let oneMillion = 1_000_000

2.忽略元组的元素值

当我们使用元组时,假设有的元素不须要使用。这时能够使用下划线将对应的元素进行忽略,比如:

  1. let http404Error = (404, "Not Found")
  2. let (_, errorMessage) = http404Error

代码中。仅仅关心http404Error中第二个元素的值。所以第一个元素能够使用下划线进行忽略。

3.忽略区间值

  1. let base = 3
  2. let power = 10
  3. var answer = 1
  4. for _ in 1...power {
  5. answer *= base
  6. }

有时候我们并不关心区间内每一项的值,能够使用下划线来忽略这些值。

4.忽略外部參数名

  1. class Counter {
  2. var count: Int = 0
  3. func incrementBy(amount: Int, numberOfTimes: Int) {
  4. count += amount * numberOfTimes
  5. }
  6. }

在上面的代码中,方法incrementBy()中的numberOfTimes具有默认的外部參数名:numberOfTimes,假设不想使用外部參数名能够使用下划线进行忽略,代码能够写为(只是为了提高代码的可读性,一般不进行忽略):

  1. class Counter {
  2. var count: Int = 0
  3. func incrementBy(amount: Int, _ numberOfTimes: Int) {
  4. count += amount * numberOfTimes
  5. }
  6. }
  1. func join(s1: String, s2: String, _ joiner: String = " ") -> String {
  2. return s1 + joiner + s2
  3. }
  4. // call the function.
  5. join(s1: "hello", s2: "world", joiner: "-")

假设不想使用默认外部參数名,能够进行例如以下改动:

  1. func join(s1: String, s2: String, _ joiner: String = " ") -> String {
  2. return s1 + joiner + s2
  3. }
  4. // call the function.
  5. join("hello", "world", "-")
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注