Why is it always possible to access the .0 element of an optional tuple in Swift?

A function in Swift makes me think 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"

As I understand it, this is due to the fact that a tuple with one type element Twill be considered as T, and not (T)vice versa, therefore, T.0indeed (T).0, which returns the first element.

What I do not understand if it Tis optional, that is, in the case T?or (T)?, at what point can you always get access to .0and get exactly it? Is this an intended function with some real business or just an inevitable byproduct?

The question is not how to “fix” it, but why this is so.

, ... T?.0 (T?).0?

+1
2
  • x , x.i i- .
  • x , x.0 (x).0 x ( x.i i > 0).

, x.0 x .

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

, ,

quux, quux.0, quux.0.0

, quux.1 - . quux! ,

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

:


...
, - . , (Int) Int, (Int).

Swift 2.1/Xcode 7.1.1: -, " " :

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

: .0 Swift?

, : .0 Swift, Swift .0 .

, , . , .

, : ? .0 Swift? , " (Int) - Int, (Int)", , , , Int (Int).

, , , , - , , , . , , . , Foo :

struct Foo<T> { let foo:T }
let myValue:Foo<Int> = Foo(foo: Int(2))

myValue , Int. , Int "" Foo - , .

, a Foo<Int> - Int , - , 1- , (Int), Int. , , a (T) T. a (T) T, a T (T). T (T), T , (T). x.0 x.

" ", , . , . ? . , . , ? . !:)

+1

Source: https://habr.com/ru/post/1616166/


All Articles