【问题标题】:Tuple with Individual element带有单个元素的元组
【发布时间】:2019-08-28 05:08:56
【问题描述】:

我有以下带有单个值的元组的语法

let http200Status = (statusCode: 200, description: "OK")
print("The status code is \(http200Status.statusCode)")

// Prints "The status code is 200"

现在,如果我将个人价值更改为

    let http200Status = (Code: 200, Code: "OK")
    print("The status code is \(http200Status.0)"). // 200
    print("The status code is \(http200Status.1)"). // 0k

    print("The status code is \(http200Status.Code)") // it prints 200
    print("The status code is \(http200Status.Code)") // it prints 200 always why not value Ok

我的问题:为什么它总是取 Code 的第一个值?不是第二个?

【问题讨论】:

  • 我编译器实际上允许你为多个元组元素分配相同的名称,你希望它以后如何区分它们?我实际上认为这是一个编译器错误,至少这应该会产生一个警告。

标签: swift xcode tuples


【解决方案1】:

接受同名元组标签是一个错误 (SR-8974)。它已在 Swift 5.1 中修复。来自CHANGELOG

不再允许重复的元组元素标签,因为它会导致错误的行为。

Xcode 11 (beta 6) 正确地抱怨:

let http200Status = (Code: 200, Code: "OK")
// Error: Cannot create a tuple with a duplicate element label

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 2016-07-31
    • 2019-01-14
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    相关资源
    最近更新 更多