为什么总是可以在 Swift 中访问可选元组的 .0 元素? [英] Why is it always possible to access the .0 element of an optional tuple in Swift?

查看:24
本文介绍了为什么总是可以在 Swift 中访问可选元组的 .0 元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Swift 中的一个特性让我好奇了一段时间……请看下面的代码:

A feature in Swift has been making me wonder for a while... see the code below:

class Clazz {
    var foo: String = "abc";
}

let foo: Int = 1
let bar: Int? = 2
let baz: Clazz? = Clazz()
let qux: Clazz = Clazz()
let quux: (Int, String)? = (1, "abc")

foo.0           //1
foo.0.0         //1
bar.0.0.0       //{Some 2} #optional
baz.0           //{{foo "abc"}} #optional
qux.0.0         //{foo "abc"}
quux.0          //{(.0 1, .1 "abc")} #optional
quux.1          //error: doesn't have a member named '1'
quux!.1         //"abc"

据我所知,这是因为只有一个 T 类型元素的元组将被视为 T 而不是 (T)反之亦然,所以 T.0 实际上是 (T).0,它返回第一个元素.

As I understand, it is because a tuple with only one element of type T will be treated as T rather than (T) and vice versa, so T.0 is really (T).0, which returns the first element.

我不明白的是,如果 T 是可选的,即在 T?(T)? 的情况下,始终可以访问 .0 并完全获取自身的意义何在?它是具有某些实际用例的预期功能,还是只是不可避免的副产品?

What I don't understand is, if T is optional, i.e. in the case of T? or (T)?, what's the point of being always possible to access .0 and gets exactly itself? Is it an intended feature with some real usecases, or just an unavoidable by-product?

问题不是如何修复"它,而是为什么会这样.

The question is not how to 'fix' it, but why it is like this.

或者,是因为我读错了... T?.0 实际上应该是 (T?).0?

Or, it's because I'm reading it wrong... T?.0 should actually be (T?).0?

推荐答案

  • 如果 x 是元组,则 x.i 返回第 i 个组件.
  • 如果 x 不是元组,则 x.0 被视为 (x).0 并返回 x(并且 x.i 是任何 i > 0 的错误).
    • If x is a tuple then x.i returns the i-th component.
    • If x is not a tuple then x.0 is treated as (x).0 and returns x (and x.i is an error for any i > 0).
    • 一个可选的不是元组,所以 x.0 为任何可选类型返回 x.这适用于您的

      An optional is not a tuple, so x.0 returns x for any optional type. This applies to your

      let quux: (Int, String)? = (1, "abc")
      

      因此

      quux, quux.0, quux.0.0
      

      都是相同的,quux.1 是一个错误.quux! 一个元组,因此

      are all identical, and quux.1 is an error. quux! is a tuple, therefore

      quux!.0 == 1
      quux!.1 == "abc"
      

      文档的相关部分:

      元组类型
      ...
      如果括号内只有一个元素,则类型就是该元素的类型.比如(Int)的类型是Int,而不是(Int).

      Swift 2.1/Xcode 7.1.1 的更新: 显然,处理任何作为单元素元组"的变量不再起作用:

      Update for Swift 2.1/Xcode 7.1.1: Apparently, treating any variable as a "one-element tuple" does not work anymore:

      let foo: Int = 1
      let bar = foo.0 // error: value of type 'Int' has no member '0'
      

      这篇关于为什么总是可以在 Swift 中访问可选元组的 .0 元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆